C# 如何通过属性获取引用当前对象的父对象类型
假设我有三个类C# 如何通过属性获取引用当前对象的父对象类型,c#,.net,C#,.net,假设我有三个类A,B和C,如下,A和B具有属性Pro1和Pro2,类型C: class A { public C Pro1 {get; set; } } class B { public C Pro2 { get; set; } } public class C { public void Do() { //How to get Type of object to reference to current object C //
A
,B
和C
,如下,A
和B
具有属性Pro1
和Pro2
,类型C
:
class A
{
public C Pro1 {get; set; }
}
class B
{
public C Pro2 { get; set; }
}
public class C
{
public void Do()
{
//How to get Type of object to reference to current object C
//Example: Either type A or B
}
}
在类C
的方法Do
中,我想获得要引用当前对象C的当前父对象(通过Pro1
和Pro2
)。在这个样本中,A或B,但一般来说,它可能是非常动态的:
var a = new A() { Pro1 = new C() };
a.Pro1.Do(); //will get Type A in Do
var b = new B() { Pro2 = new C() };
b.Pro2.Do(); //with get Type B in Do
哪种方法可以实现这一点?您可以将“parent”对象作为参数传递给C构造函数:
public class C
{
private readonly object _parent;
public C(object parent)
{
_parent;
}
public void Do()
{
Type type = _parent != null ? _parent.GetType() : null;
// Do something with type...
}
}
这样,您已经知道哪个对象正在进行调用(a或b);你现在所做的可能没有意义。如果是这样,您总是可以通过简单的继承来解决这个问题
C a=new A();
C b=new B();
而且可以将调用方的身份插入到CTOR A或B中。Thomas Levesque提供了一种向
C
添加更多信息的方法。如果它是要存储在C
中的类型而不是特定实例,则可以将C
设置为泛型,如中所示:
class A
{
public C<A> Pro1 { get; set; }
}
class B
{
public C<B> Pro2 { get; set; }
}
public class C<T> where T : class // maybe you want to add other "where" constraints on T
{
public void Do()
{
// you can use T in here
}
}
A类
{
公共C Pro1{get;set;}
}
B类
{
公共C Pro2{get;set;}
}
公共类C其中T:class//也许您想在T上添加其他“where”约束
{
公营部门
{
//你可以在这里用T
}
}
您在Do
中做什么?有更干净的方法来实现这种行为(A
&B
实现一个公共接口并传递它们,例如),而不是对类型做出反应,因为类型很快就会变得丑陋。@AustinSalonen:我试图从这个问题中找出答案,并将我引向这一点:就像导致这个问题的原始问题一样,如果不重新定义类,就没有直接的方法来完成所要求的任务。可能添加泛型类型参数,可能添加某种类型的接口,等等。如果您保持问题中所写的类,那么C实例就无法知道它是从A.Pro1还是B.Pro2获得的。例如,这两个属性返回的对象甚至可能是完全相同的对象!我在你链接的Mattias的问题中添加了一个新建议。希望这能让他走上正轨。
class A
{
public C<A> Pro1 { get; set; }
}
class B
{
public C<B> Pro2 { get; set; }
}
public class C<T> where T : class // maybe you want to add other "where" constraints on T
{
public void Do()
{
// you can use T in here
}
}