Casting type in C # using an object type string name

I have the following code that should easily trace through

public class Foo { public void FooHasAMethod() { Console.WriteLine("it is me, foo!!!"); } } public class Bar { public Foo FooProperty { get; set; } } public class FooBar { public static void Main() { Bar bar = new Bar{ FooProperty = new Foo() }; CallPropertyByName(bar, "Foo"); } public static void CallPropertyByName(Bar bar, string propertyName) { PropertyInfo pi = bar.GetType().GetProperty(propertyName + "Property"); object fooObj = pi.GetValue(bar, null); ((Foo)fooObj).FooHasAMethod(); // this works /* but I want to use * ((Type.GetType(propertyName))fooObj).FooHasAMethod(); This line needs fix * which doesnt work * Is there a way to type cast using a string name of a object? * */ } } 
+4
source share
4 answers
 Type fooObjType = fooObj.GetType(); MethodInfo method = fooObjType.GetMethod("FooHasAMethod"); method.Invoke(fooObj, new object[0]); 
+4
source

If you are using .NET 4, it is really very simple = D

 dynamic obj = bar; obj.FooProperty.FooHasAMethod(); 

However, if you just want to pass the result to another type, you can do this at run time using the Convert.ChangeType method:

 object someBoxedType = new Foo(); Bar myDesiredType = Convert.ChangeType(typeof(Bar), someBoxedType) as Bar; 

Now it has a strong connection with the actual types Foo and Bar. However, you can generalize the method to get what you want:

 public T GetObjectAs<T>(object source, T destinationType) where T: class { return Convert.ChangeType(typeof(T), source) as T; } 

Then you can call like this:

 Bar x = GetObjectAs(someBoxedType, new Bar()); SomeTypeYouWant x = GetObjectAs(someBoxedType, Activator.CreateInstance(typeof("SomeTypeYouWant"))); 

Using an activator, you can create at runtime any type you want. And the general method is fooled by output in an attempt to convert from your boxedType to a runtime type.

Also, if you just want to call the method for some dynamic property value, then it would be best practice (imo) to simply pass it as some desired object.

 ISomething propValue = obj.GetProperty("FooPropery").GetValue(obj, null) as ISomething; if(propValue != null) propValue.FooHasAMethod(); 
+6
source

Unable to pass type unknown at compile time.

Look at the .NET 4.0 dynamic type.

+5
source

There is no way to cast using a string. But you can use dynamic or MethodInfo with a call

+1
source

Source: https://habr.com/ru/post/1347124/


All Articles