C# 在运行时生成泛型类型

C# 在运行时生成泛型类型,c#,generics,reflection,types,runtime,C#,Generics,Reflection,Types,Runtime,我想知道是否可以将一个变量的类型设置为另一个泛型变量的类型 例如,假设我有以下代码: public class Foo: IBar<ushort> { public FooBar() { Value = 0; } public ushort Value { get; private set; } } 那么在我的代码中我有这个 var myFoo = new Foo(); var fooDataType = myFoo.Value.G

我想知道是否可以将一个变量的类型设置为另一个泛型变量的类型

例如,假设我有以下代码:

public class Foo: IBar<ushort>
{
    public FooBar()
    {
        Value = 0;
    }

    public ushort Value { get; private set; }
}
那么在我的代码中我有这个

var myFoo = new Foo();
var fooDataType = myFoo.Value.GetType();

//I know this line of code does not compile, but this is what I am looking to be able to do
var myFooDTO= new FooDTO<fooDataType>();

我所寻找的可能吗?由于使用反射,对于高使用率的代码来说会不会太慢。

您可以通过反射,通过使用


由于反射,这将有一些开销,因此您需要对其进行分析,以确定这是否会成为您的问题。

您正在寻找编译时反射,这是C没有的特性。因此,如果您正在寻找性能优化,那么解决方案比问题更糟糕

但它确实有这个特点;你写起来很容易

int x = 0;
typeof(x) y = x + 2;

或者更复杂的D表达式,都是在编译时计算的。

当我在一句话中阅读泛型和运行时时,我总是觉得设计不好或者不理解泛型的含义。可能两者都有

泛型参数是该类型不可分割的一部分。所以说在运行时生成泛型类型和在运行时生成Foo类是一样的。您要么在寻找反射,要么在改变算法的设计


在这种情况下,var关键字也不会帮助您。忘掉它。

为什么不使用方法类型推断:

public class FooDTO<TType> {
    public TType Value { get; private set; }
}

public class Foo : FooDTO<ushort> { }

static FooDTO<T> GetTypedFoo<T>(T Obj) {
    return new FooDTO<T>();
}

static void Main(string[] args) {
   Foo F = new Foo();

   var fooDTO = GetTypedFoo(F.Value);
}

你想要的核心是:

var type = typeof(FooDTO<>).MakeGenericType(fooDataType);
object obj = Activator.CreateInstance(type);

当然,您可以将运行时/泛型的点击向上移动-可能会移动到泛型方法中;然后泛型方法中的所有内容都可以使用T,您可以使用MakeGenericMethod在特定T的上下文中执行该方法,该特定T只有在运行时才知道。

为什么?你想做什么?应该是@Object,或者更好的obj。我写了同样的东西,所以我给你一个+1。
public class FooDTO<TType> {
    public TType Value { get; private set; }
}

public class Foo : FooDTO<ushort> { }

static FooDTO<T> GetTypedFoo<T>(T Obj) {
    return new FooDTO<T>();
}

static void Main(string[] args) {
   Foo F = new Foo();

   var fooDTO = GetTypedFoo(F.Value);
}
var type = typeof(FooDTO<>).MakeGenericType(fooDataType);
object obj = Activator.CreateInstance(type);
IBar bar = (IBar)Activator.CreateInstance(type);