C# use reflection to get method name [duplicate] - c#-4.0

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
get methodinfo from a method reference C#
This is most likely something simple but so far I have not come up with anything on how to do this.
I want to be able to get the name of a method in two different ways. Please note I want a method name, not a property name.
1) Inside of a class like ClassA<T>, looking like:
var name = GetMethodName(x => x.MethodA);
2) Outside of a class, looking like:
var name = GetMethodName<ClassA<object>>(x => x.MethodA);
var name = GetMethodName<ClassB>(x => x.MethodB);
How might I do this exactly?
Thanks!

You don't need lambdas (x => x.MethodA, etc). That's just confusing the issue (and hiding the method of interest: the MethodA bit would be hidden from your GetMethodName method).
Instead, you can use reflection to get a MethodInfo object, which then has a Name property.
For example:
MethodInfo sm = typeof(SomeClass).GetMethod("SomeMethod");
string methodName = sm.Name;
Here methodName will be the string "SomeMethod". (Of course, in this simple case we've used the class name to get the MethodInfo object, so it's somewhat circular and we might as well have just used the hard-coded "SomeMethod" string instead!)

Related

How to reference a class from a string which is part of a variable 3.7

I have just read a text file and extracted a string and stored it as a variable. This string also happens to be the name of a class I want to reference in order to use in a function for example. The "which_class" variable is the whichever class was stored in the file
I tried passing the which_class variable in as a parameter to the function. Removing the quotations seems to make it work but I am unsure how to do this.
class needed_for_func_one():
multiplier = 1.23
class needed_for_func_two():
multiplier = 1.15
def random_function(which_class):
print(123 * which_class.multiplier)
PSEUDO CODE
READ FROM FILE STORE STRING AS "which_class"
which_class = "needed_for_func_two"
random_function(which_class)
But this didn't work it just gave me an attribute error
the eval function could help you here.
random_function(eval(whichClass))
However, you should probably rethink whether you really want to it that way or if there is a much cleaner solution.
I think your question is related to this one
How you call the function depends if it is a global function or if it is inside an object.
globals()['call_this_function']() # this is probably what you need
or
getattr(from_this_object, 'call_this_function')()
first, to use a class you need an object of a class.
so if what you read is a name of the class or any other thing it does not matter, just use an if statement to decide what is inside that variable so-called "which_class".
then create an object like :
if which_class=="needed_for_func_one":
newObject = needed_for_func_one()
elseif which_class=="needed_for_func_two":
newObject = needed_for_func_two()
then use the print like :
print(123 * newObject.multiplier )

Groovy - Set your own property of an Integer

I just started to learn Groovy and wondering if you can set your own property for an integer. For example,
def a = 34.5.plus(34.34)
def b = 5.64.minus(3.43)
def c = 12.64.multiply(33.43)
In the above there are certain methods like plus minus and multiply
What should I do if I want to define some of my own methods for integers like that.
I searched Google but couldn't find much about it.
Sure, you can just add methods to the metaClass of Integer.
Here's an example:
Integer.metaClass.zeds = { -> 'z' * delegate }
assert 3.zeds() == 'zzz'
You can also add methods to a single instance of integer should you wish to, ie:
Integer num = 4
num.metaClass.halved = { -> delegate / 2.0 }
assert num.halved() == 2.0
You can also add methods to classes via Extension Methods a good explanation of which can be found over here
It should be noted (as you originally tagged this question as Java) that obviously, Java code will have no knowledge of these things, as it doesn't know about the metaClass
Use groovy meta programming, this allows you to create dynamic method creation atruntime in the class that you want to place in .
bydefault if a method is not found methodmissing exception throws , this is where groovy allows you add method at runtime for more reference use the below comprehensive link
http://groovy-lang.org/metaprogramming.html
If this answer helps , dont forget to click answered.

Casting to types that are know only at Runtime by their string names. C#

I've got a problem here. (C#)
There's a collection in another assembly (I cannot change it) that takes a string as parameter and returns an object.
Like:
object Value = ThatCollection.GetValue("ParameterName");
The problem is, for each parameter string, it returns a DIFFERENT type as object.
What I want is to cast those objects to their respective types, knowing the types only at runtime by their string names.
I need to do some operations with those returned values.
And for that I need to cast them properly in order to access their members and so.
Limitations:
I cannot use "dynamic" since my code needs to be done in an older framework: 3.5 (because of interop issues).
I need to do operations with MANY returned values of different types (no common interfaces nor base classes, except "object", of course)
All I have is a table (containing string values) correlating the parameter names with their returned types.
Yes, I could transform that table into a biiig "switch" statement, not very nice, don't want that.
Any hints??
You want to look into reflection, something like the following should work to cast an object to type T. Set up a simple cast method:
public static T CastToType<T>(object o)
{
return (T)o;
}
Invoke this using reflection:
Type t = Type.GetType(stringName)
MethodInfo castTypeMethod = this.GetType().GetMethod("CastToType").MakeGenericMethod(t);
object castedObject = castTypeMethod .Invoke(null, new object[] { obj });

Vala: Pass String as Class

Scenario:
I have x number of classes. Lets say 10; Each class does different UI Functions. When a user loads a file, that extension tells the program the classname to load; but it's in the form of a string.
Is there anyway to pass a string off as a classname? Something to the effect of.
var classname = "Booger";
var nose = new classname(){ //classname really means "Booger"
//Do Operation
}
You can reflect a type by name using var t = Type.from_name(classname);, however, this works on all types, including enums and structs and it might be the type Type.INVALID. You should probably do some checks, like t.is_a(typeof(MyParentClass)).
You can then instantiate a copy using var obj = Object.new(t);. The whole thing would look like:
var classname = "Booger";
var t = Type.from_name(classname);
if (t.is_a(typeof(MyParentClass)))
return Object.new(t);
else
return null;
It's also worth noting that the run-time type names have the namespace prepended, so you might want to do "MyNs" + classname. You can check in either the generated C or doing typeof(MyClass).name().
I've had the same problem as the OP in regards to getting an assertion error against null. If you take a look at the Glib documentation (in C) it mentions you have to register your class by actually specifying the class name first before you can actually use a string representation of your class name.
In other words you have to use your class first BEFORE you can instantiate a copy of your class with Glib.Type.from_name ("ClassName").
You can use your class first by instantiating a class instance or by getting type information for your class.
var type = typeof (MyClass);
var type_from_string = Type.from_name ("MyClass");
Furthermore, when you use Object.new to create a class there are two things you need to be aware of:
1) You need to cast the return value to get your specific class or base class.
var instance_of_my_class = Object.new (type) as MyClass;
2) Constructors for your class will no longer be called (I don't why). You will need to use the GObject style constructor inside your class:
construct {
pizza = 5;
}

Groovy type conversion

In Groovy you can do surprising type conversions using either the as operator or the asType method. Examples include
Short s = new Integer(6) as Short
List collection = new HashSet().asType(List)
I'm surprised that I can convert from an Integer to a Short and from a Set to a List, because there is no "is a" relationship between these types, although they do share a common ancestor.
For example, the following code is equivalent to the Integer/Short example in terms of the
relationship between the types involved in the conversion
class Parent {}
class Child1 extends Parent {}
class Child2 extends Parent {}
def c = new Child1() as Child2
But of course this example fails. What exactly are the type conversion rules behind the as operator and the asType method?
I believe the default asType behaviour can be found in: org.codehaus.groovy.runtime.DefaultGroovyMethods.java
org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.java.
Starting from DefaultGroovyMethods it is quite easy to follow the behavior of asType for a specific object type and requested type combination.
According to what Ruben has already pointed out the end result of:
Set collection = new HashSet().asType(List)
is
Set collection = new ArrayList( new HashSet() )
The asType method recognizes you are wanting a List and being the fact HashSet is a Collection, it just uses ArrayList's constructor which takes a Collection.
As for the numbers one, it converts the Integer into a Number, then calls the shortValue method.
I didn't realize there was so much logic in converting references/values like this, my sincere gratitude to Ruben for pointing out the source, I'll be making quite a few blog posts over this topic.

Resources