【问题标题】:How does this code work? Accessing property through another property [closed]这段代码是如何工作的?通过另一个属性访问属性[关闭]
【发布时间】:2018-08-03 21:18:54
【问题描述】:

所以这是代码:

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

那究竟是在做什么?有人可以解释一下吗?

【问题讨论】:

  • 它被称为reflection。谷歌首发:the docs
  • PropertyType 是一个Type 对象 - 它基本上是关于类型的元数据(您可以想象它对于在运行时检查对象很有用 - “反射”) - 关于其名称等的信息等。在这里,您将类型的名称写入控制台。有问题的类型对象是您在GetProperties 期间枚举的任何属性的类型。例如 - 它可能是一个获取/设置 string 值的属性。 Type 对象将是 System.String 的描述符,并将描述来自 System.String 的属性、方法、声明程序集等。
  • PropertyType.Name 将返回名称所暗示的内容。属性类型名称,lol。
  • 查看这里了解您所掌握的内容:msdn.microsoft.com/en-us/library/system.type
  • 不不不。我的问题完全不同。这与反射无关。关于这行代码: property.PropertyType.Name 这里到底发生了什么?我如何访问三个成员我无法理解这里发生了什么。

标签: c# oop properties


【解决方案1】:

假设有以下类:

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 将通过返回分配给PropB 实例返回"The Name"

您可以将其分解为更长的形式,以获取有关访问如何工作的示例,并从生产力的角度了解链接调用的帮助。

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

【讨论】:

    猜你喜欢
    • 2015-04-04
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多