5
sTypeName = ... //do some string stuff here to get the name of the type

/*
The Assembly.CreateInstance function returns a type
of System.object. I want to type cast it to 
the type whose name is sTypeName.

assembly.CreateInstance(sTypeName)

So, in effect I want to do something like:

*/

assembly.CreateInstance(sTypeName) as Type.GetType(sTypeName);

我怎么做?而且,假设这是 C# 2.0,我在赋值表达式的左侧取什么?我没有 var 关键字。

4

3 回答 3

2

不幸的是,.NET 中没有办法做你想做的事。

可能的部分解决方案是:

  1. 如果您在编译时知道类型(不太可能,因为您是在运行时从字符串创建它),那么只需转换为该类型:

    YourType t = (YourType)Activator.CreateInstance(sTypeName);
    
  2. 如果您知道所有可能的类型都将实现特定的通用接口,那么您可以转换为该接口:

    IYourInterface i = (IYourInterface)Activator.CreateInstance(sTypeName);
    

如果您不能做到以上任何一项,那么不幸的是,您会陷入object反思。

于 2010-04-15T09:08:10.683 回答
2

通常你让所有的类,你想动态地实例化它,实现一个通用的接口,比如说IMyInterface。您可以像这样从类名字符串创建一个实例:

Assembly asm = Assembly.GetExecutingAssembly();
string classname = "MyNamespace.MyClass";
Type classtype = asm.GetType(classname);

// Constructor without parameters
IMyInterface instance = (IMyInterface)Activator.CreateInstance(classtype);

// With parameters (eg. first: string, second: int):
IMyInterface instance = (IMyInterface)Activator.CreateInstance(classtype, 
                        new object[]{
                            (object)"param1",
                            (object)5
                        });

即使您没有通用接口,但知道方法的名称(作为字符串),您也可以像这样调用您的方法(对于属性、事件等非常相似):

object instance = Activator.CreateInstance(classtype);

int result = (int)classtype.GetMethod("TwoTimes").Invoke(instance, 
                        new object[] { 15 });
// result = 30

示例类:

namespace MyNamespace
{
    public class MyClass
    {
        public MyClass(string s, int i) { }

        public int TwoTimes(int i)
        {
            return i * 2;
        }
    }
}
于 2010-04-15T09:13:17.313 回答
2

.

在你的类中定义一个泛型方法,然后你可以像这样进行转换:

 public T Cast<T>(object obj)
 {
      return (T) obj;
 }

 string sTypename = "SomeClassName"; 
 MethodInfo cast = this.GetType().GetMethod("Cast");
 MethodInfo genericCast = cast.MakeGenericMethod(new Type[] { Type.GetType(sTypename) });
 Object castedValue = genericCast.Invoke(this, new object[] { instanceToBeCasted });

但是我想,如果您不能将转换后的值存储在实际类型的变量中,那么这种转换有什么意义呢?正是因为您在编写代码时不知道实际类型?

于 2010-11-30T10:39:09.647 回答