有没有办法在匿名类型上调用模板化的类?

时间:2016-08-03 06:32:41

标签: c# generics anonymous-types

这里有一些代码可以提供这个想法。

public class C<T> { }
public class X {
  void M() {
    var V = new { W = 1 };
    var X = new C<V>(); // illegal
  }
}

所以V是一个匿名类型的变量,我想用V作为参数实例化C类。这需要一个我无法提供的类型参数。

这个问题很相似,但答案在我的案例中帮助不大:Why can't I instantiate a generic class inferring types from anonymous objects?

问题背后的问题是我正在尝试做IEnumerable可以做的事情。

应该说清楚:我真的不想通过操纵objectType来做到这一点,因为你失去了强类型和智能感知的好处。

对于任何感兴趣的人,需要此项目的项目如下所述:http://www.andl.org/2016/07/andl-net-making-progress/

3 个答案:

答案 0 :(得分:4)

如果您有工厂方法,则可以使用类型推断:

public class C<T>
{
    public C(T t)
    {
        // ...
    }
}

public static class Factory
{
    public static C<T> Create<T>(T t)
    {
        return new C<T>(t);
    }
}

public class Thing
{
    void Foo()
    {
        var x = new { y = "z" };
        //var thing = new C(x); - doesn't work, you need to specify the generic parameter
        var thing = Factory.Create(x); // T is inferred here
    }
}

答案 1 :(得分:1)

你不能这样做,因为V是匿名类型的实例,而不是类型名称本身。

您可以动态创建此类型(假设C&lt;&gt;中的无参数构造函数):

var X = typeof (C<>)
            .MakeGenericType(V.GetType())
            .GetConstructor(Type.EmptyTypes)
            .Invoke(new object[0]);

答案 2 :(得分:0)

您需要类型,您可以使用传递对象作为类型。

示例代码:

public class C<T> 
{
    public T _t { get; set; }

    public C(T t)
    {
        _t = t;
    }

    public void TestMethod()
    {
        Console.WriteLine(_t.ToString());
    }
}

public class X
{
    public void M()
    {

        var V = new { W = 1 };

        var X = new C<object>(V); // everything is an object.

        X.TestMethod();
    }
}