简体   繁体   English

在C#中访问匿名类型的属性?

[英]Accessing properties of an anonymous types in C#?

Say I created an anonymous type for person that has name and birth date as properties: 假设我为具有姓名和出生日期的人创建了一个匿名类型:

var person = new{ Name = "Mike", BirthDate = new DateTime(1990, 9, 2) };

then later on, decided to add a method that will return the age of the person. 然后,后来决定添加一种方法来返回该人的年龄。

var person = new { Name = "Mike", 
                   BirthDate = new DateTime(1990, 9, 2), 
                   GetAge = new Func<int>(() => { return /* What? */; }) };

How do I access the property BirthDate so that I can compute the age? 如何访问属性BirthDate以便可以计算年龄? I tried using this but of course it didn't work. 我尝试使用this但是当然没有用。

You can't. 你不能 You will have to create a Person class to have such functionality: 您将必须创建一个Person类以具有以下功能:

    class Person {
        public string Name { get; set; }
        public DateTime BirthDate { get; set; }
        public TimeSpan Age {
            get {
                // calculate Age
            }
        }
    }

    var person = new Person {
            Name = "Mike",
            BirthDate = new DateTime(1990, 9, 2))
    };

Edit: Another option is to create an extension method for DateTime : 编辑:另一个选项是为DateTime创建扩展方法

    public static TimeSpan GetAge(this DateTime date) {
        // calculate Age
    }

    var person = new {
            Name = "Mike",
            BirthDate = new DateTime(1990, 9, 2))
    };

    TimeSpan age = person.BirthDate.GetAge();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM