繁体   English   中英

如何通过C#中的参数获取属性的对象实例?

[英]How can I get a property's object instance through a parameter in C#?

如何通过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#中实现。 我浏览了Reflection API,但仍然不确定应该使用什么功能。

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

将属性值传递给方法时,例如:

SomeMethod(obj.TheProperty);

然后将其实现为:

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

基本上,您不能从中获得父对象。 您将需要分别传递它,例如:

SomeMethod(obj, obj.TheProperty);

此外,请记住,值可以是任意数量的对象的一部分。 字符串实例可用于零个,一个或“许多”对象中。 您所要求的基本上是不可能的。

暂无
暂无

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

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