【问题标题】:How can I get a property's object instance through a parameter in C#?如何通过 C# 中的参数获取属性的对象实例?
【发布时间】:2012-10-11 08:52:33
【问题描述】:

如何通过 C# 中的参数获取属性的对象实例?我不确定它是否称为变量实例,但这就是我的意思:

在通常情况下,当我们这样做时,我们会在 C# 中获取变量的值:

void performOperation(ref Object property) {
   //here, property is a reference of whatever was passed into the variable
}

Pet myPet = Pet();
myPet.name = "Kitty";
performOperation(myPet.name);   //Here, what performOperation() will get is a string

我希望实现的是从类的属性中获取对象,比如:

void performOperation(ref Object property) {
   //so, what I hope to achieve is something like this:

   //Ideally, I can get the Pet object instance from the property (myPet.name) that was passed in from the driver class
   (property.instance().GetType()) petObject = (property.instnace().GetType())property.instance();  

    //The usual case where property is whatever that was passed in. This case, since myPet.name is a string, this should be casted as a string
   (property.GetType()) petName = property;   
}

Pet myPet = Pet();
myPet.name = "Kitty";
performOperation(myPet.name);   //In this case, performOperation() should be able to know myPet from the property that was passed in

instance() 只是一个虚拟方法,用于演示我想要获取属性的实例对象。我对 C# 很陌生。这在概念上是我希望实现的,但我不确定如何在 C# 中做到这一点。我查看了反射 API,但仍然不太确定应该使用什么来执行此操作。

那么,如何在 C# 中通过参数获取属性的对象实例呢?

【问题讨论】:

  • 我很确定您必须将对象和属性传递给performOperation。
  • 那么我无法从属性本身获取属性的对象实例吗?
  • 我不这么认为,至少不是您在示例中访问该属性的方式。
  • 我明白了。是的,我在示例中访问该属性的方式仅仅是我的意图的一个说明,因为我不确定我应该如何去做。我对 C# 的语法也有些陌生。谢谢。 :)
  • 如果您获得该属性的PropertyInfo。然后您可以使用DeclaringType property 获取声明成员的class,但看起来您无法获取实例。

标签: c# reflection instance-variables


【解决方案1】:

当你将一个属性值传递给一个方法时,例如:

SomeMethod(obj.TheProperty);

然后实现为:

SomeType foo = obj.TheProperty;
SomeMethod(foo);

基本上,您无法从中获取父对象。您需要单独传递它,例如:

SomeMethod(obj, obj.TheProperty);

另外,请记住,一个值可以是任意数量个对象的一部分。字符串实例可以用在零个、一个或“许多”对象中。你问的基本上是不可能的。

【讨论】:

    猜你喜欢
    • 2011-01-20
    • 2013-01-02
    • 1970-01-01
    • 2014-02-04
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多