object - 如何将 Activator.CreateInstance 返回的对象转换为它转换的类型?

标签 object types instance

在下面的代码中,是否可以将 x 转换为您传递给 Activator.CreateInstance 的类型,而无需提前知道它是什么?我尝试传入 typeof... 但这不起作用。

var testClasses = AppDomain.CurrentDomain.GetAssemblies()
                  .Single(a=>a.FullName.StartsWith("VerifyStuff")).GetTypes()
                  .Where(t=>t.UnderlyingSystemType.Name.StartsWith("VerifyXXX"));

var x = Activator.CreateInstance(testClasses.ElementAt(0));

谢谢!

最佳答案

你只需要转换它:

MyObject x = (MyObject) Activator.CreateInstance(testClasses.ElementAt(0));

当然,如果您在 testClasses 中有各种类型,这将变得更加困难。如果它们都派生自相同的基类或实现相同的接口(interface),那么您可以强制转换为该基类或接口(interface)。

编辑:

is it possible to convert x to the type you're passing into Activator.CreateInstance without knowing what it is ahead of time?

只是为了更加说明:x 您传递给 CreateInstance 的类型,但它被转换为对象,因为 CreateInstance 不知道您可以向它扔什么。你的问题发生在你创建了你的具体实例之后 - 你不能将它传递给另一个(强类型)函数,因为你将它作为一个对象。有几种解决方法:

  • 正如我上面提到的,让它们都派生自相同的基类或接口(interface),这样您就可以将它们作为该基类或接口(interface)类型传递

  • 如果您有一个函数需要对这些具体实例执行操作,请创建一个通用函数来执行此操作:

    
    public T MyFunc(T myConcreteInstance) 
    {
        ... do whatever it is i need to do...
    }
    
  • 这很丑陋,但可能很难避免...在对它们进行操作之前使用大的 if..else if 语句来确定它们的类型(提示:避免这种情况使用上面的选项 #1...):

    
    Type t = myConcreteInstance.GetType();
    if (t == typeof(someType1))
    {
    
    }
    else if (t == typeof(someType2))
    {
    
    }
    ... etc ...
    

如果此时您在想“为什么我不做一个 CreateInstance() 的通用版本?” 那么别费心了 - 已经有一个了,它仍然没有解决您在传递事物之前强类型化的问题。引用 MSDN:

In general, there is no use for the CreateInstance in application code, because the type must be known at compile time. If the type is known at compile time, normal instantiation syntax can be used (new operator in C#, New in Visual Basic, gcnew in C++).

如果您打算使用 CreateInstance,那是因为您事先不知道类型,因此您必须解决它。

关于object - 如何将 Activator.CreateInstance 返回的对象转换为它转换的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5751108/

相关文章:

apache-flex - actionscript 3 的数据类型大小

haskell - 未强制执行函数返回类型

php - 什么时候使用 getInstance/new class() 比较合理? (PHP)

javascript - 对象属性作为哈希函数中的键值对

php - 如何一次只获取一个键值对? PHP

c++ - C++中如何存储静态数据和方法细节

c++ - 错误 : Conversion from 'double' to non-scalar type 'Player' requested in function 'int main()' ;

java - 对java中对象的双重引用

php - 如何检测匿名类的实例?

javascript - 评估模板字符串和类实例