简体   繁体   English

未知的C#类型

[英]Unknown C# type

I've a method exMethod that return the value in this way: 我有一个方法exMethod以这种方式返回值:

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 ). 匿名类型不能跨越方法的边界传递而不会丢失其类型(它们将恢复为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) (我不想提到dynamic作为解决方案)

you could do 你能做到的

dynamic person = exMethod();

but not recommended and is 'the easy way out' and you wouldn't have any compile time errors then. 但不推荐,并且是“简单的出路”,那么你就不会有任何编译时错误。 Another solution could be to use reflection but that can be heavy. 另一种解决方案可能是使用反射,但这可能很重。

The best (safest, best practice) idea is probably to create a class to define the type that is being returned 最好(最安全,最佳实践)的想法可能是创建一个类来定义返回的类型

class Foo {
    public string name {get;set;}
    public string surname{get;set;}
}

return new Foo(){ name = name, surname = surname }

then you would be able to use those properties 那么你就可以使用这些属性了

If you have control over exMethod , modify it as Patrick suggests . 如果您可以控制 exMethod ,请按照 Patrick的建议进行修改。

If you don't and must accept it as an Object use dynamic instead of var : 如果你不这样做, 必须接受它作为 Object使用 dynamic而不是 var

 
 
 
 
  
  
  dynamic person = exMethod(); person.name;
 
 
  

Answer is worthless, comments are good, particularly @Servy's: 答案毫无价值,评论很好,特别是@Servy:

Anonymous classes are internal, so if it's in an API that you don't have access to then dynamic wouldn't work. 匿名类是内部的,因此如果它在您无法访问的API中,那么dynamic将无效。 It's only an option when you have control over the implementation of the method. 当您控制方法的实现时,它只是一个选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM