C# C中程序集的类型实例化#

C# C中程序集的类型实例化#,c#,reflection,types,C#,Reflection,Types,有可能这样做吗 创建一个类并将其放入程序集中,例如 namespace some { public class foo{ ..etc } 将其加载到当前appdomain Assembly.LoadFrom("some.foo.dll"); 把字拿出来 Type t = Type.GetType("some.foo"); 基本上还是有办法把实际的类型输入t?我不确定我是否理解这个问题。我认为您需要实例化该类型 这将调用公共默认构造函数: // specify

有可能这样做吗

  • 创建一个类并将其放入程序集中,例如

    namespace some
    {
        public class foo{
            ..etc
    }
    
  • 将其加载到当前appdomain

    Assembly.LoadFrom("some.foo.dll");
    
  • 把字拿出来

    Type t = Type.GetType("some.foo");
    

  • 基本上还是有办法把实际的类型输入t?

    我不确定我是否理解这个问题。我认为您需要实例化该类型

    这将调用公共默认构造函数:

    // specify the full name and assembly name, to make sure that you get the some.foo
    // from the assembly in question.
    Type t = Type.GetType("some.foo, some.foo");
    object instance = Activator.CreateInstance(t);
    
    Type.GetType("Foo").GetConstructor().Invoke();
    

    查看重载以调用其他构造函数。

    您可以使用反射来实例化对象。例如,要使用默认构造函数进行实例化:

    // specify the full name and assembly name, to make sure that you get the some.foo
    // from the assembly in question.
    Type t = Type.GetType("some.foo, some.foo");
    object instance = Activator.CreateInstance(t);
    
    Type.GetType("Foo").GetConstructor().Invoke();
    
    要使用接受字符串的构造函数进行实例化,请使用:

    Type.GetType("Foo").GetConstructor(new[] { typeof(string) }).Invoke(new [] { "bar" });
    

    这可能类似于您想要的:对于“实际类型”,您是指一个实例吗?我不确定我是否理解您的问题。也许您想执行
    var a=Assembly.LoadFrom(“some.foo.dll”)var t=a.GetType(“some.foo”)?是的,这正是我想要表达的:)我想我犯的错误是我假设了汇编。Load会将类型直接加载到appdomain中。谢谢。CreateInstance并没有创建一个完全类型的foo,如果你想用foo.cast类型作为foo传递它,你必须将它强制转换为什么?动态加载程序集时,通常不知道类型。否则就直接调用构造函数。至少有一个接口是有意义的,但问题不在于此。当你知道
    Foo
    时,为什么不直接调用
    newfoo()
    ?这很好。我将从示例中删除该变量,因为正如您所说,我们假设我们不知道foo。