如何定义一个属性,以在不实例化对象的情况下从中读取属性?

问题描述

| 假设我有
class Person
{
[ColumnAttribute(\"ID\"]
    public int Id;
[ColumnAttribute(\"Name\"]
public string Name;
[ColumnAttribute(\"DateOfBirth\"]
    public date BirthDate;
}
我想读取某些属性属性,但不实例化Person对象。比如说我想读取Name属性上定义的属性,但是我希望它像ReadAttribute(Person.Name)一样不创建对象。 我为什么要那样?因为此Person对象是我正在创建的框架的Entity对象,所以我希望能够定义要对DAL层的返回进行排序的列。 我不想传递字符串,因为那样一来,当我更改数据库时,字符串将不同步。 那有可能吗? dal的功能是Person.GetAllByAge(int Age,/ somesome here,我想定义排序/) 如果还有其他方法可以解决此问题,我将很高兴听到它。我当时在考虑使用表达式树,但我也被困在那里。 谢谢 编辑: 谢谢大家的s骂,但问题不在于读取属性。 我想在打电话给dal时打电话给类似的人 Dal.Person.GetAllByAge(25,BirthDate) 这将返回所有25岁的人,按姓名排序 目前可以通过致电 Dal.Person.GetAllByAge(25,\“ DateOfBirth \”) 谢谢     

解决方法

除了Pete M \的答案,您还可以将
IEnumerable<T>.OrderBy
中使用的
Func<T1,T2>
传递到您的方法中,并在方法中进行排序
public IEnumerable<Person> GetAllByAge<T>(int age,Func<Person,T> orderBy)
{
   var people = ... (get your collection of \'age\' aged people here)
   return people.OrderBy(orderBy);
}
用法将是
Dal.Person.GetAllByAge(25,p => p.BirthDate)
    ,是的,我定义了一个扩展方法,使其变得更简单,所以我可以只叫
typeof(Person).GetAttributes<CollumnAttribute>()
        /// <summary>
    /// Loads the configuration from assembly attributes
    /// </summary>
    /// <typeparam name=\"T\">The type of the custom attribute to find.</typeparam>
    /// <param name=\"typeWithAttributes\">The calling assembly to search.</param>
    /// <returns>An enumeration of attributes of type T that were found.</returns>
    public static IEnumerable<T> GetAttributes<T>(this Type typeWithAttributes)
        where T : Attribute
    {
        // Try to find the configuration attribute for the default logger if it exists
        object[] configAttributes = Attribute.GetCustomAttributes(typeWithAttributes,typeof(T),false);

        // get just the first one
        if (configAttributes != null && configAttributes.Length > 0)
        {
            foreach (T attribute in configAttributes)
            {
                yield return attribute;
            }
        }
    }
    ,是否有特定原因强制对
GetAllByAge()
方法本身进行排序?为什么不将其归还后就立即排序呢?逻辑顺序是否需要在服务器端发生?我将返回一个
List<Person>
(您提到自己动手做),并使用LINQ根据需要订购该套装,除非我有很好的理由不这样做:
Dal.Person.GetAllByAge(25).OrderBy(p => p.BirthDate);
    ,无需实例化“ 10”对象,这绝对是可行的。您将要使用Reflection访问属性,特别是
GetCustomAttributes
方法。 这是供参考的文章。 您的最终结果可能看起来像这样:
System.Attribute[] attrs = System.Attribute.GetCustomAttributes(typeof(Person));  // Reflection.
    ,属性不允许使用lambda作为参数,因此不幸的是无法使用“ 13”。在类似的情况下,我使用枚举将事物链接在一起。 就我的目的而言,这工作得很好,但仍然会导致某些代码重复(作为枚举声明)。但是,这确实解决了字符串文字的问题,现在您可以安全地重构代码了。