[英]How can I get a property's object instance through a parameter in C#?
How can I get a property's object instance through a parameter in C#? 如何通过C#中的参数获取属性的对象实例? I'm not sure if it's called a variable instance, but here's what I meant:
我不确定是否将其称为变量实例,但这是我的意思:
In the usual case, when we do this, we get the value of the variable in 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
What I hope to achieve, is to get the object from the property of the class, like say: 我希望实现的是从类的属性中获取对象,例如:
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
The instance()
is just a dummy method to demonstrate that I want to get the property's instance object. instance()
只是一个虚拟方法,用以演示我要获取属性的实例对象。 I am very new to C#. 我是C#的新手。 This is conceptually what I wish to achieve but I am not sure how I could do so in C#.
从概念上讲,这是我希望实现的目标,但是我不确定如何在C#中实现。 I looked through the Reflection API but I'm still not very sure what I should use to do this.
我浏览了Reflection API,但仍然不确定应该使用什么功能。
So, how can I get a property's object instance through a parameter in C#? 那么,如何通过C#中的参数获取属性的对象实例?
When you pass a property value to a method, for example: 将属性值传递给方法时,例如:
SomeMethod(obj.TheProperty);
Then it is implemented as: 然后将其实现为:
SomeType foo = obj.TheProperty;
SomeMethod(foo);
You cannot get the parent object from that, basically. 基本上,您不能从中获得父对象。 You would need to pass that separately, for example:
您将需要分别传递它,例如:
SomeMethod(obj, obj.TheProperty);
Additionally, keep in mind that a value can be part of any number of objects. 此外,请记住,值可以是任意数量的对象的一部分。 A string instance could be used in zero, one, or "many" objects.
字符串实例可用于零个,一个或“许多”对象中。 What you ask is fundamentally not possible.
您所要求的基本上是不可能的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.