简体   繁体   中英

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#? 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#:

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. I am very new to C#. This is conceptually what I wish to achieve but I am not sure how I could do so in C#. I looked through the Reflection API but I'm still not very sure what I should use to do this.

So, how can I get a property's object instance through a parameter in 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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