我有一个返回对象的方法:
private object myObjectMethod(){
//...
return myObject;
}
Run Code Online (Sandbox Code Playgroud)
但在另一种方法中,我想要检索此对象:
private void myotherMethod(){
var x = myObjectMethod();
// Now how would I access the properties of myObject?
}
Run Code Online (Sandbox Code Playgroud)
最好的方法是从方法中返回您正在处理的实际类型
但是,如果这不是一个选项,并且你真的被困在只是object从你的方法返回,你有几个选择.
如果你知道正确的类型,那么铸造将是最简单的方法:
((ActualType)x).SomeProperty;
或者测试演员是否正确:
string val;
if (x is ActualType)
val = (x as ActualType).SomeProperty;
Run Code Online (Sandbox Code Playgroud)
或者,如果您知道属性名称,但不知道x的类型,那么:
PropertyInfo pi = x.GetType().GetProperty("SomeProperty");
string somePropertyValue = (string)pi.GetValue(x, null);
Run Code Online (Sandbox Code Playgroud)
或者,如果您使用的是C#4,则可以使用 dynamic
string somePropertyValue = ((dynamic)x).SomeProperty;
Run Code Online (Sandbox Code Playgroud)
只是不要动态疯狂. 如果您发现自己dynamic过度使用,则代码可能存在一些更深层次的问题.
更改
private object myObjectMethod(){
...
return myObject;
}
Run Code Online (Sandbox Code Playgroud)
至
private TypeOfMyObject myObjectMethod(){
...
return myObject;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1822 次 |
| 最近记录: |