Reflecting a private field from a base class

You can manually go up in the inheritance chain to get the base fields: Given these classes: class SuperClass1 { private int myField; } class SuperClass2 : SuperClass1 { } class MyClass : SuperClass2 { } This should work: var myObj = new MyClass(); var myField = typeof(MyClass).BaseType .BaseType .GetField(“myField”, BindingFlags.Instance | BindingFlags.NonPublic); There’s a … Read more

How to use Activator to create an instance of a generic Type and casting it back to that type?

Since the actual type T is available to you only through reflection, you would need to access methods of Store<T> through reflection as well: Type constructedType = classType.MakeGenericType(typeParams); object x = Activator.CreateInstance(constructedType, new object[] { someParameter }); var method = constructedType.GetMethod(“MyMethodTakingT”); var res = method.Invoke(x, new object[] {someObjectThatImplementsStorable}); EDIT You could also define an additional … Read more

Find methods that have custom attribute using reflection

Your code is completely wrong. You are looping through every type that has the attribute, which will not find any types. You need to loop through every method on every type and check whether it has your attribute. For example: var methods = assembly.GetTypes() .SelectMany(t => t.GetMethods()) .Where(m => m.GetCustomAttributes(typeof(MenuItemAttribute), false).Length > 0) .ToArray();

How to get the name of a function in Go?

I found a solution: package main import ( “fmt” “reflect” “runtime” ) func foo() { } func GetFunctionName(i interface{}) string { return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name() } func main() { // This will print “name: main.foo” fmt.Println(“name:”, GetFunctionName(foo)) }

Get derived class type from a base’s class static method

This can be accomplished easily using the curiously recurring template pattern class BaseClass<T> where T : BaseClass<T> { static void SomeMethod() { var t = typeof(T); // gets type of derived class } } class DerivedClass : BaseClass<DerivedClass> {} call the method: DerivedClass.SomeMethod(); This solution adds a small amount of boilerplate overhead because you have … Read more