var 的类型(不使用动态)?
可能的重复:
如何将匿名类型传递给方法?< /a>
我试图识别匿名类型的类型。
List<int> lst = new List<int> {1, 2, 3, 4, 5};
var myVarType = from item in lst select new {P = item*item, P2 = item + "###"};
foreach (var k in myVarType)
{
Console.WriteLine(k.P + " " + k.P2);
}
现在我想要将部分代码转移到函数中,但它尖叫着他不知道类型- 这是合乎逻辑的,因为 var 在编译时是已知的,并且他不知道编译时的类型:
我不想想使用动态||元组。
正如您所知, var 作为 func 参数类型是不可接受的。
但是,我曾经读到过有一个技巧
可以让我将匿名类型
转移到myFunc
。
我认为这是乔恩·斯基特或埃里克·利珀特的作品。
帮助 ?
编辑
看看我的自我回答。 我在这里找到的 匿名类的返回类型是什么
Possible Duplicate:
How can I pass an anonymous type to a method?
Im trying to recognize the type of the anonymous type.
List<int> lst = new List<int> {1, 2, 3, 4, 5};
var myVarType = from item in lst select new {P = item*item, P2 = item + "###"};
foreach (var k in myVarType)
{
Console.WriteLine(k.P + " " + k.P2);
}
Now i want a part of code to be transferred to a function but it screams that he doesnt know the type - which is logical since var is to be known at compile time and he doesnt know the type at compile :
I dont want to use dynamic || Tuples.
and as you know var is not acceptable as a func param type.
But , Ive once read that there is a trick
which lets me transfer to myFunc
the anonymous type
.
I think it was by Jon skeet or Eric lippert.
Help ?
edit
look at my self answer.
I found it here
What's the return type of an anonymous class
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该类型是“生成的”,您可能能够在运行时通过反射获取它,但它将包含您不能在名称中使用的字符。
您可以使用元组:
The type is 'generated' and you might be able to get it at run-time with reflection but it will contain characters you can't use in a name.
You could use Tuples:
使方法通用,这应该可行。
编辑
正如评论中提到的,您无法访问属性。您可以在此处使用委托来访问属性或使用动态(您不想使用)。
Make the method generic, this should work.
Edit
As mentioned in comments you can't access the properties. You could use here a delegate to access the properties or use dynamic ( which you don't want to use ).
这是我找到的代码
的返回类型是什么匿名类
here is the code which i found
What's the return type of an anonymous class