开发者

Get the parent class of a null object (C# Reflection)

开发者 https://www.devze.com 2022-12-23 10:58 出处:网络
How would I get the parent class of an object that has a value of null? For example... ClassA contains int? i which is no开发者_C百科t set to any value when the class is created.

How would I get the parent class of an object that has a value of null?

For example...

ClassA contains int? i which is no开发者_C百科t set to any value when the class is created.

Then in some other place in the code I want to pass in i as a parameter to some function. Using i as the only info, I want to be able to figure out that ClassA "owns" i.

The reason for this is because ClassA also contains some other object, and I want to call this other object's value from that same function mentioned in the above paragraph.

Could also be:

public class A
{
    public class B
    {
        public int? i;
        public int? j;
    }

    B classBInstance = new B();
    public string s;
}

{
    ...
    A someClassAInstance = new A();
    ...
    doSomething(someClassAInstance.classBInstance.i);
    ...
}

public static bool doSomething(object theObject)
{
    string s = /* SOMETHING on theObject to get to "s" from Class A */;
    int someValue = (int)theObject;
}


You can't. Pass an instance of A to doSomething.


class A is not the Parent (base) of its members. Just their holder.

So you cannot do what you want, passing an int or int? around doe not involve any information about the class.


The parameter that is sent to the method doesn't contain any information that you can use to determine which object it originally came from. What's sent to the method is just a copy of the nullable int, boxed in an object.

So what you are asking for is not possible. The only way to do something like that would be to analyse the call stack to find the calling method, then analyse the code in that method to determine where the parameter value was taken from.


Cant you use a dictionary or keyvaluepairs instead so that the int is linked to "s" that way? The problem is that an int is not aware of which object owns it.


Its not possible since you are passing 'i' which is a member of class B. But class B does not hold a reference to an instance of class A. An instance is required to get the value of 's' since its a non-static field.

0

精彩评论

暂无评论...
验证码 换一张
取 消