.net 从实例化的系统中获取类型参数T。类型?

.net 从实例化的系统中获取类型参数T。类型?,.net,types,type-parameter,.net,Types,Type Parameter,我有特定对象的System.Type,但需要将其作为类型参数T传递给另一个方法。。。这有可能吗?还是我迷失在更大的画面中了?你可以通过反射来实现这一点 难道你不想改变你的设计吗(以避免反冲)?因此,您可以将类型作为参数传递: DoSomething(yourObject.GetTaype()); 考虑使用替代设计。泛型类型旨在在编译时进行静态解析 不过,这是可能的。你需要进行反思: public class TypeReporter<T> { public TypeRepo

我有特定对象的System.Type,但需要将其作为类型参数T传递给另一个方法。。。这有可能吗?还是我迷失在更大的画面中了?

你可以通过反射来实现这一点

难道你不想改变你的设计吗(以避免反冲)?因此,您可以将类型作为参数传递:

DoSomething(yourObject.GetTaype());

考虑使用替代设计。泛型类型旨在在编译时进行静态解析

不过,这是可能的。你需要进行反思:

public class TypeReporter<T> {
    public TypeReporter() {
        Console.WriteLine("this type is: {0}", typeof(T));
    }

    // other methods
}

public class StackOverflow694683 {
    static void Main() {
        string n = "..."; // Pick a type, such as System.String.
        Type arg = Type.GetType(n);
        Type genericClass = typeof(TypeReporter<>);
        Type createdClass = genericClass.MakeGenericType(arg);

        // Result is of TypeReporter<T> type. Invoke desired methods.
        object result = Activator.CreateInstance(createdClass);
    }
}
公共类TypeReporter{
公共打字机(){
WriteLine(“此类型为:{0}”,typeof(T));
}
//其他方法
}
公共类堆栈溢出694683{
静态void Main(){
string n=“…”;//选择一个类型,例如System.string。
类型arg=Type.GetType(n);
类型genericClass=typeof(TypeReporter);
类型createdClass=genericClass.MakeGenericType(arg);
//结果为TypeReporter类型。请调用所需的方法。
对象结果=Activator.CreateInstance(createdClass);
}
}

这是不可能的。仔细想想,类型参数是在编译时解析的,而System.Type是在运行时通过反射解析的

现在,已经说过这是不可能的,通过使用反射,这是可能的。如果您创建了带有反射的类,您可以将其作为参数传入System.Type,但无论您尝试做什么,它都值得重新设计

编辑:这里有一些重新设计的想法

System.Type从何而来?您能否将其作为类型参数本身传递,以便可以传递


如果没有,您能否制作一个适配器来处理将要使用的已知类型?可能是从System.Type转换为正确类型的泛型调用的switch语句?任何事情都比反射快。

你要求做的事在.Net中是不可能的。类型参数是.Net(C#和VB)中的编译类型操作。然而,System.Type实例是一个运行时构造。任何关于System.type背后的实际类型的查询都必须在运行时进行。因此,这些解决方案是不兼容的

例如:

public void DoSomething<T>(T value) {
  // Do something with a value of type T
}

public Example1() {

  DoSomething(42);  // Calls DoSomething<int>
  Type t1 = typeof(int);
  DoSomething(t1);  // Calls DoSomething<Type>

  object o1 = 42;
  Type t2 = o1.GetType();
  DoSomething(???)  // No way to call DoSomething<int> here without some
                    // wild reflection because the call to DoSomething is
                    // established at compile type where t2 is established
                    // at runtime
}
public void DoSomething(T值){
//使用类型为T的值执行某些操作
}
公共示例1(){
DoSomething(42);//调用DoSomething
类型t1=类型of(int);
DoSomething(t1);//调用DoSomething
对象o1=42;
类型t2=o1.GetType();
DoSomething(???)//如果没有一些
//疯狂的思考,因为对做某事的呼吁是
//在编译类型上建立,其中t2已建立
//运行时
}

您通常要做的是为专门用于这些类型操作的泛型方法设置重载。例如:

Load<T>();
Load(Type type);
Load();
荷载(类型);

你能发布你的代码样本吗?这是-I-通常做的,但是该方法是第三方的,它只接受SomeMethod();结构。。。这就是为什么我要问。。