获取空对象的父类(C# 反射)
如何获取值为 null 的对象的父类?
例如...
ClassA
包含 int? i
在创建类时未设置为任何值。
然后在代码中的其他地方我想将 i
作为参数传递给某个函数。使用 i
作为唯一信息,我希望能够找出 ClassA
“拥有”i
。
这样做的原因是因为 ClassA
还包含一些其他对象,并且我想从上一段中提到的同一函数调用这个其他对象的值。
也可以是:
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;
}
How would I get the parent class of an object that has a value of null?
For example...
ClassA
contains int? i
which is not 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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是不可能的,因为您传递的“i”是 B 类的成员。但是 B 类不保存对 A 类实例的引用。需要一个实例来获取 's' 的值,因为它是非静态场。
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.
你不能使用字典或键值对来代替,以便 int 以这种方式链接到“s”吗?问题是 int 不知道哪个对象拥有它。
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.
发送到该方法的参数不包含任何可用于确定它最初来自哪个对象的信息。发送到该方法的只是可空 int 的副本,装箱在对象中。
所以你所要求的是不可能的。执行类似操作的唯一方法是分析调用堆栈以查找调用方法,然后分析该方法中的代码以确定参数值的来源。
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.
类 A
不是其成员的父级(基类)。只是他们的持有者。因此,您不能做您想做的事,传递
int
或int?
不涉及有关该类的任何信息。class A
is not the Parent (base) of its members. Just their holder.So you cannot do what you want, passing an
int
orint?
around doe not involve any information about the class.你不能。将
A
的实例传递给doSomething
。You can't. Pass an instance of
A
todoSomething
.