是否可以创建匿名通用对象?

时间:2017-10-20 19:57:37

标签: c#

想象一下,你想要声明一个匿名类型的对象,但你需要它是通用的(我不能想到一个实际的原因,这是理论上的)。你会如何创建这样的对象?

例如:

diff

编辑:

var anonymousGeneric = new <T>{ }; // <- doesn't work

var anonymousGeneric = Activator.CreateInstance((new { }).GetType()); // Not generic 

结束编辑

但这些都不奏效。当然,这个想象问题的现实解决方案是定义一个实际的类定义:

// because:
(new { }).GetType().IsGenericType == false
// Of course, any useful anonymous object _will_ be generic:
(new { a="b" }).GetType().IsGenericType == true
// But in the process of testing various aspects of this question 
// it had never occurred to me that I needed to supply any property 
// (this was all theoretical, remember)

但这并不像上面那样匿名。

创建对象后,可以考虑稍后使用它:

public GenericThing<T> { }

总之,是否可以创建匿名通用对象?

2 个答案:

答案 0 :(得分:3)

  

(我无法想出实际的原因,这是理论上的)

在这种情况下,让我们坚持简单明了,因为它更容易找到原因:只需从通用方法创建一个常规的匿名对象。

public object Foo<T>(T t) { return new { t }; }

此处,Foo(0)Foo("")必然会返回不同的类型,但它们仍会共享类型定义。

非常任何使用匿名类型都可以在泛型方法中有同等意义。

答案 1 :(得分:1)

anonymousGeneric.GetType()返回错误类型的泛型类型:Closed (with type parameter(s)) vs open (without) 1 。如果要更改类型参数,则需要从中获取泛型类型定义。

以下实际上有效,但我无法想象它对任何人有什么好处 2

var anonymousGeneric = new {a = "b"};

var anonymousGenericType = anonymousGeneric.GetType().GetGenericTypeDefinition();

var intThingType = anonymousGenericType.MakeGenericType(typeof(int));

var intThingInstance = Activator.CreateInstance(intThingType, 9);

现在我们有一个类似anonymousGeneric的东西,但它的类型参数是int而不是string,它的a属性是9.但它有什么用呢? ?你如何声明它的引用?如果你手上有时间,你可以在XAML中绑定它的属性。

1 感谢Amy和Servy投入,以清除我对术语的困惑。

2 请注意,天上和地上的事物比我的哲学中所梦想的更多。