[英]Get Anonymous Type from Object Type
For the code shown below 对于下面显示的代码
using System;
public class Test
{
public static void Main()
{
Test t = new Test();
object AnonymousInside= t.GetAnonymousType();
Console.Write(AnonymousInside.Key);//Error on compilation
}
public object GetAnonymousType()
{
return new {Key="KeyName",Value="ValueName"};
}
}
How can I take the anonymous type back from type object
? 如何从类型object
取回匿名类型?
If that is not possible then how this code works? 如果不可能,那么这段代码如何工作?
@Html.TextBoxFor(model => model.ConfirmPassword, new { maxlength = 35, type = "password", @class="textArea margindrop",placeholder="Confirm password"})
Its Documentation 它的文件
You can make it dynamic 您可以使其动态
dynamic AnonymousInside= t.GetAnonymousType();
Though you should use a class,struct instead 虽然您应该使用类,但应改用struct
If you still want to use anonymous type 如果您仍然想使用匿名类型
It's mentioned in the docs : 在文档中提到了它:
The compiler provides a name for each anonymous type, although your application cannot access it. 编译器为每种匿名类型提供一个名称,尽管您的应用程序无法访问它。
So,the only way to access it through object would be using reflection
or dynamic
因此,通过对象访问它的唯一方法是使用reflection
或dynamic
If you do not want to use dynamic
you may try something like this 如果您不想使用dynamic
,则可以尝试这样的操作
using System;
public class Test
{
public static void Main()
{
var AnonymousInside = GetAnonymousTyped(GetAnonymousObject(), new {Key="",Value=""});
Console.Write(AnonymousInside.Key);//All Ok
}
public static T GetAnonymousTyped<T>(object o, T _)
{
return (T)o;
}
public static object GetAnonymousObject()
{
return new {Key="KeyName",Value="ValueName"};
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.