本文介绍了未知的C#类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个方法 exMethod
返回的值是这样的:
返回新{名称=名字,姓氏=姓};
和我用这个code
变种人= exMethod();
但在这一点上,我怎么能访问到它的领域?我试着以
person.name
但引发的异常
对象不包含名称的定义
解决方案
匿名类型不能在方法的边界通过,而不会失去它们的类型(它们将恢复到对象
)。既然你可以不投它,你被卡住。
您必须创建一个类型暴露出的创作方法的外面。 (我不想提动态
作为一个解决方案)
I've a method exMethod
that return the value in this way:
return new {name = name, surname = surname};
and I use this code
var person = exMethod();
but at this point how can I access to its fields? I've tried with
person.name
but is thrown the exception
'object' does not contain a definition for 'name'
解决方案
Anonymous types can't be passed across the boundaries of a method without losing their type (they will revert to object
). Since you can't cast it, you are stuck.
You have to create a type to expose that to the outside of the creating method. (I don't want to mention dynamic
as a solution)
这篇关于未知的C#类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!