充分利用匿名类型的价值? [英] Getting value from anonymous type?
问题描述
比方说,我们已经得到了下面的方法:
公共对象测试()
{
返回新{A =测试};
}
有没有得到存储在:一种价值的机会?
变种b =测试(); //任何机会,以施放此匿名类型?
注意,返回匿名类型或元组LT;>
从方法是一个坏的事情
但是,你问一个关于如何的问题做到这一点,不是它是一个不错的主意...
通过使用动态或反射...
动态b =测试();
字符串str = b.A;
以欺骗或者:
公共静态对象的测试()
{
返回新{A =测试};
}
公共静态字符串木屐(obj对象)
{
//我们创建一个匿名类型同类型之一,测试的()
//只是为了有它的类型。
变种x =新的{A =的String.Empty};
//我们通过它来投,将采取它的T从X
中的类型//,并且将返回OBJ铸造匿名
的类型//类型
X = CAST(X,OBJ);
//现在以x我们已经OBJ,但强类型。所以x.A是价值,我们
//想
返回x.A;
}
公共静态牛逼演员LT; T>(T型,obj对象),其中T:类
{
回报率(T)OBJ;
}
字符串str =木屐(测试());
在C#中所有的匿名类型与在同一个程序集是同一类型的相同属性合并在一起。因此,新{A}
测试()
和的木屐()
是同一类型的
的
演员LT; T>
是一个有用的技巧来提取从匿名类型的类型。你传递作为第一个参数您键入的匿名类型(参数仅用于激活普通的 T
),并为对象要投的第二个参数。类似的技巧可以用来创建泛型类型的集合,像
公共静态牛逼MakeList< T>(T型)
{
返回新的List< T>();
}
Let's say we've got the following method:
public object Test()
{
return new { A = "Test" };
}
Is there a chance of getting the value that is stored in A?
var b = Test(); //Any chance to cast this to the anonymous type?
Note that returning anonymous types or Tuple<>
from a method is a bad thing to do
But you asked a question about how to do it, not about "is it a good idea"...
By using dynamic or reflection...
dynamic b = Test();
string str = b.A;
Or by cheating:
public static object Test()
{
return new { A = "Test" };
}
public static string GetA(object obj)
{
// We create an anonymous type of the same type of the one in Test()
// just to have its type.
var x = new { A = string.Empty };
// We pass it to Cast, that will take its T from the type of x
// and that will return obj casted to the type of the anonymous
// type
x = Cast(x, obj);
// Now in x we have obj, but strongly typed. So x.A is the value we
// want
return x.A;
}
public static T Cast<T>(T type, object obj) where T : class
{
return (T)obj;
}
string str = GetA(Test());
In C# all the anonymous types with the same properties of the same type that are in the same assembly are merged together. So the new { A }
of Test()
and of GetA()
are of the same type.
The Cast<T>
is a useful trick to extract the type from an anonymous type. You pass as the first parameter your typed anonymous type (the parameter is used only to "activate" the generic T
) and as the second parameter the object you want to cast. Similar tricks can be used to create collections of generic types, like
public static T MakeList<T>(T type)
{
return new List<T>();
}
这篇关于充分利用匿名类型的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!