简体   繁体   English

使用对象类型的字符串名称在C#中进行类型转换

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

I have the following code, should be easy to follow 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?
         * */
    }
}

If you're using .NET 4, it's actually really easy =D 如果您使用的是.NET 4,则实际上非常简单= 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: 但是,如果您只想将结果转换为其他类型,则可以在运行时使用Convert.ChangeType方法执行此操作:

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. 现在,这与实际类型Foo和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. 泛型方法被推论诱骗,试图将boxedType转换为运行时类型。

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. 另外,如果只想对某个动态属性值调用方法,则最佳实践(imo)将只是将其强制转换为某些所需对象。

ISomething propValue = obj.GetProperty("FooPropery").GetValue(obj, null) as ISomething;

if(propValue != null)
    propValue.FooHasAMethod();

It is not possible to cast to a type not known at compile-time. 无法将其转换为编译时未知的类型。

Have a look at the .NET 4.0 dynamic type. 看一下.NET 4.0 动态类型。

Type fooObjType = fooObj.GetType();
MethodInfo method = fooObjType.GetMethod("FooHasAMethod");
method.Invoke(fooObj, new object[0]);

There's no way to cast by using string. 无法通过使用字符串进行强制转换。 But you can use dynamic , or MethodInfo with invoke 但是您可以将dynamicMethodInfo与invoke一起使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM