Type casting in c# using the string name of the object type

后端 未结 4 1998
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-05 19:42

I have the following code, should be easy to follow through

public class Foo
{
    public void FooHasAMethod()
    {
        Console.WriteLine(\"it is me, fo         


        
相关标签:
4条回答
  • 2021-01-05 20:10

    There's no way to cast by using string. But you can use dynamic, or MethodInfo with invoke

    0 讨论(0)
  • 2021-01-05 20:12

    It is not possible to cast to a type not known at compile-time.

    Have a look at the .NET 4.0 dynamic type.

    0 讨论(0)
  • 2021-01-05 20:16
    Type fooObjType = fooObj.GetType();
    MethodInfo method = fooObjType.GetMethod("FooHasAMethod");
    method.Invoke(fooObj, new object[0]);
    0 讨论(0)
  • 2021-01-05 20:19

    If you're using .NET 4, it's actually really easy =D

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

    However, if you just want to cast the result to some other type, you can do that at runtime with the Convert.ChangeType method:

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

    Now, this one has a strong link to the actual types Foo and Bar. However, you can genericize 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 invoke like so:

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

    Using the activator, you can at runtime create any type you want. And the generic method is tricked by inference into attempting a convert from your boxedType to the runtime type.

    In addition, if you want to just call a method on some dynamic property value, then the best practice (imo), would be to simply cast it as some desired object.

    ISomething propValue = obj.GetProperty("FooPropery").GetValue(obj, null) as ISomething;
    
    if(propValue != null)
        propValue.FooHasAMethod();
    
    0 讨论(0)
提交回复
热议问题