提取对象的价值? [英] Extract value from Object?
问题描述
我想让我在其中传递的对象我做的任何实例动态方法,例如:
I wanted to make a dynamic method in which i pass any instance of object i made, for example:
public class Employee()
{
public string FName;
public string SName;
.....etc.
}
我要的方法是这样的:
The method i want is like the following:
public void methodName(Object oObject)
{
//lets say that i have passed object employee to it.
}
是否有可能从oObject提取任何价值,我试图这样做,但它没有属性,这样做,当我把手表,我可以实际上可以看到类别的雇员,所有的属性在里面。
Is it possible to extract any values from the oObject, i have tried to do so but it have no attributes to do so, and when i put in the watch i can acutally see all the attribute of class employee in it.
那么,有什么办法?
推荐答案
<击>有很多种方法。击>
更新:你说你要整个对象。 铸造或接口暴露的属性就是这样向前的。
Update: you say you want the whole object. Casting or interfaces to expose the properties is the way foward.
您可以把对象的具体类型:
You can cast the object to the specific type:
if (oObject is Employee)
{
string name = (oObject as Employee).FName;
}
您可以公开定义方法的期望的接口,然后提供类型实现的接口:
You can expose an interface that defines what the method expects, then provided types implement the interface:
public interface IFirstName
{
string FName { get; }
}
public void methodName(IFirstName objectWithFirstName)
{
string name = objectWithFirstName.FName;
}
您可以使用动态
,并希望最好在运行时(.NET 4):
You can use dynamic
and hope for the best at runtime (.NET 4):
public void methodName(dynamic oObject)
{
string name = oObject.FName;
}
再有就是反思。
但更好的问题要问的是,这是一个好方法吗?我是有点怀疑关于采取任何方法,使事情的期待......虽然这并不是说,它不会或不应该发生的。
But the better question to ask is, is this a good method? I would be a little skeptical about methods that take anything and make expectations about things... though that's not to say it doesn't or shouldn't happen.
这篇关于提取对象的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!