如何定义一个属性来读取从属性,而不instantionating对象? [英] How do I define a property to read an attribute from, without instantionating an object?

查看:71
本文介绍了如何定义一个属性来读取从属性,而不instantionating对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有:

class Person
{
[ColumnAttribute("ID"]
    public int Id;
[ColumnAttribute("Name"]
public string Name;
[ColumnAttribute("DateOfBirth"]
    public date BirthDate;
}

我想读一些财产,但没有instantionating Person对象的属性。例如说,我想阅读关于名称property.But定义我希望它是这样的ReadAttribute(Person.Name),而无需创建一个对象的属性。

I want to read the attribute on some property but without instantionating the Person object. Say for example I want to read the attribute defined on Name property.But I want it to be like that ReadAttribute(Person.Name) without creating an object.

为什么我要那个?因为这个Person对象是一个框架,我创建一个实体对象,我希望能够定义上,我想从DAL层返回排序的列。

Why do I want that? because this Person object is a Entity object for a framework I am creating, and I want to be able to define the column on which I want to sort the return from the DAL Layer.

我不希望传递一个字符串,因为这样的字符串将不同步的,当我更改数据库等。

I don't want to pass strings because that way the string will get out of sync when I change the database and so on.

所以,这可能吗?的dal的功能是Person.GetAllByAge(INT年龄,/的不知何故在这里我要定义排序的/)结果
。如果有另一种方式来解决这个问题,我会很高兴听到它。 。结果
谢谢,我想用表达式树也许,但我坚持有太多

So is this possible? The function of the dal is Person.GetAllByAge(int Age, /somehow here I want to define the sorting/)
If there is another way to fix this problem I will be happy to hear it. I was thinking of using expression tree maybe, but I am stuck there too.
thanks

谢谢大家answearing但问题是不是读的属性。调用DAL调用类似的东西,结果
Dal.Person.GetAllByAge(当结果
I希望25,出生日期)结果
这将返回所有这些都是25岁按名称搜索$ b $排序b本可以通过调用结果
Dal.Person目前做的人。 GetAllByAge(25日,出生日期)结果​​
感谢

thank you all for answearing but the question is not about reading attributes.
i want when calling the dal to call something like that
Dal.Person.GetAllByAge(25, BirthDate)
this will return all the persons which are 25 years old sorted by name
this can be done currently by calling
Dal.Person.GetAllByAge(25, "DateOfBirth")
thanks

推荐答案

在除的皮特M的答案你可以通过 Func键< T1,T2> 的IEnumerable< T> .OrderBy 进入你的方法,并你的方法中为了

In addition to Pete M's answer you could pass the Func<T1,T2> used in IEnumerable<T>.OrderBy into your method, and order within your method

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)

这篇关于如何定义一个属性来读取从属性,而不instantionating对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆