这段代码是如何工作的?通过其他财产访问财产

时间:2018-02-23 18:35:52

标签: c# oop properties

所以这就是代码:

class Program
{
    static void Main(string[] args)
    {
        Type T = Type.GetType("CSharpLearningPurposes.Program");

        PropertyInfo[] properties = T.GetProperties();

        foreach (PropertyInfo property in properties)
        {
            Console.WriteLine(property.PropertyType.Name);
        }

    }
}

更具体地说,问题是这行代码: Console.WriteLine(propert.PropertyType.Name);

你在这里看到我访问property.PropertyType好吧我知道我正在访问该对象的成员但我不明白这一点:property.PropertyType.Name

究竟做了什么?有人可以解释一下吗?

1 个答案:

答案 0 :(得分:0)

假设以下类:

public class A {
    public B Prop {get;set;}
}

public class B {
    public string Name {get;set;}
}

如果您的A设置实例如此:

var example = new A { Prop = new B { Name = "The Name" } };

然后example.Prop.Name会返回"The Name",并返回B分配给Prop的实例。

您可以将其分解为更长的形式,以获得访问如何工作的示例,并从生产力的角度看看如何将调用链接起来是有用的。

B propVal = example.Prop;
string nameVal = propVal.Name;
Console.WriteLine(nameVal == example.Prop.Name); // True