在类中获取类型成员

本文关键字:取类型 成员 获取 | 更新日期: 2023-09-27 18:04:32

我有两种类型,定义如下:

public class T1
{
    public int A1;
    public int B1;
}
public class T2
{
    public int A2;
    public int B2;
}

我有一个包含T1和T2列表的类:

public class Topology
{
    public List<T1> T1s;
    public List<T2> T2s;
}

我想在T2类中创建一个方法,并想达到t1的变量。我怎么能做到呢?

在类中获取类型成员

如何通过构造函数传递T1引用到T2 ?

public class T2
{
    private T1 _t1Reference;
    public int A2;
    public int B2;
    public T2(T1 t1Reference)
    {
       _t1Reference = t1Reference;    
    }
    public void T2Method()
    {
       //Access _t1Reference here 
    }
}

或者通过T2的方法参数传递对T1实例的引用?

public class T2
{
    public int A2;
    public int B2;
    public void T2Method(T1 t1Reference)
    {
       //Access t1Reference here 
    }
}

在T2中创建一个公共方法,并在参数中传递T1的对象

public class T2
{
    public int A2;
    public int B2;
    public void YourMethod(T1 t1)
    {
       string a1 = t1.A1;
       string b1 = t1.B1;
    }
}

一些实现方法

1-从T1继承T2,

2-传递T1作为方法参数