C#是否可以从属性实例获取属性路径? [英] C# is it possible to get property path from property instance?

查看:74
本文介绍了C#是否可以从属性实例获取属性路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我有一个属性A的实例,对象B里面有对象C等。

现在我需要获得完整的属性路径A => (C.B.A)。



我该怎么做? Thanx。

Hi all,

I have an instance of a property A inside object B which inside object C etc.
And now I need to get a full path of property A => (C.B.A).

How can I do this? Thanx.

推荐答案

你好,



请检查StackTrace Class



@jafc
Hello,

Please check StackTrace Class.

@jafc


不,你不能做你想做的事。

再看你对José的评论你的例子:

Nope, you can't do what you seem to want.
Looking again at your example from the comment to José:
public class A { public SomeType v get {new SomeType(); } }
public class B { public A a {get {new A(); }} }
public class C { public B b {get {new B(); }} }

public class Test { 
  public void Foo(object prop) { 
    if(typeof(SomeType).IsAssignableFrom(prop.GetType()))
      // Get prop path using StackTrace
  };
  // Assuming you actually meant this:
  public Test() {
    Foo(new C().b.a.v);
  }
}



当调用Foo时,会传递一个SomeType实例,该实例是在A的v属性的getter中创建的。 />
该实例绝对没有知识创建者

Foo可用的信息与:


When Foo is called it is passed an instance of SomeType, created in the getter of the v property of A.
That instance has absolutely no knowledge of who created it.
The information available to Foo is exactly the same as for:

Foo(new SomeType());



你的链中的每个属性getter创建一个对象的新实例并在之前返回它调用下一个属性getter,所以即使StackTrace也无济于事。

在这种情况下,调用chain是顺序的,而不是嵌套的,因此堆栈中没有任何用处。


Each of the property getters in your "chain" creates a new instance of an object and returns it before the next property getter is called so even StackTrace will not help.
The call "chain" in this case is sequential, not nested, so there's nothing useful in the stack.


这篇关于C#是否可以从属性实例获取属性路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆