C# 如何在类对象中获取具有类成员的类对象
在Unix中,有一个宏C# 如何在类对象中获取具有类成员的类对象,c#,C#,在Unix中,有一个宏container\u of,它允许在引用容器结构的一个成员时检索对容器结构的引用。在C#中是否有类似的方法来实现这一点 例如,如果我有一个类Test,其中有一个成员我知道,head,有没有一种方法可以直接从对head的引用中获取对包含Test实例的引用 我看到了反射,但我认为它不起作用: public class Test{ public int a; public LinkedList<int> head; } static void m
container\u of
,它允许在引用容器结构的一个成员时检索对容器结构的引用。在C#中是否有类似的方法来实现这一点
例如,如果我有一个类Test
,其中有一个成员我知道,head
,有没有一种方法可以直接从对head
的引用中获取对包含Test
实例的引用
我看到了反射,但我认为它不起作用:
public class Test{
public int a;
public LinkedList<int> head;
}
static void main(string[] args)
{
Test t = new Test(){
a = 0,
head = new LinkedList<int>(),
};
var myHead = t.head; // how can I get "t" from here?
}
公共类测试{
公共INTA;
公众联络主任;
}
静态void main(字符串[]参数)
{
测试t=新测试(){
a=0,
head=新链接列表(),
};
var myHead=t.head;//如何从这里获取“t”?
}
如果你不自己实现它,你就不能
在C#中,对象引用是“单向的”。通过引用,您可以访问它指向的对象。但是有了这个对象,您就无法访问存储在某处的对它的引用——这仅仅是因为对同一对象的引用可能有数千个分布在AppDomain
甚至超出其边界
Test
类的对象持有对LinkedList
实例的引用,该引用存储在head
字段中。但是没有什么可以阻止您将相同的引用存储到其他地方
考虑以下代码:
var list = new LinkedList<int>();
var test1 = new Test
{
head = list
};
var test2 = new Test
{
head = list
};
var list=newlinkedlist();
var test1=新测试
{
head=列表
};
var test2=新测试
{
head=列表
};
现在,对象
test1
和test2
中都引用了LinkedList
实例。您希望从该对象接触到什么“家长”?请看,这样做行不通。这是最接近属性父级的方法:
class Program
{
static void Main(string[] args)
{
Parent parent = new Parent();
parent.AddChild();
Parent childParent = parent.Children[0].Parent;
parent.AddChild();
}
}
public class Parent
{
public List<Child> Children { get; set; }
public Parent()
{
Children = new List<Child>();
}
public void AddChild()
{
Children.Add(new Child(this));
}
}
public class Child
{
public Parent Parent { get; set; }
public Child(Parent parent)
{
Parent = parent;
}
}
类程序
{
静态void Main(字符串[]参数)
{
父项=新父项();
parent.AddChild();
Parent-childParent=Parent.Children[0]。Parent;
parent.AddChild();
}
}
公共类父类
{
公共列表子项{get;set;}
公共家长()
{
Children=新列表();
}
public void AddChild()
{
添加(新子项(此));
}
}
公营儿童
{
公共父级{get;set;}
公共子(父/母)
{
父母=父母;
}
}
如果进行调试,您将看到两个父实例引用同一个对象,并且两个子实例的计数都会使用System.Collections.Generic.LinkedListI更新yes我不理解这个问题,你想通过t.head中的1个元素访问对象t吗?像这样的东西的用例是什么?真的不清楚你在问什么,你想实现什么?忘了指针和其他东西吧,你的目标是什么?如果你只得到了你的成员
头
引用的对象,那么你无法确定它是从哪里得到的(来自名为测试
的对象中的成员)。