How do I define a property to read an attribute from, without instantionating an object?

前端 未结 5 1421
名媛妹妹
名媛妹妹 2021-01-23 10:00

Suppose I have:

class Person
{
[ColumnAttribute(\"ID\"]
    public int Id;
[ColumnAttribute(\"Name\"]
public string Name;
[ColumnAttribute(\"DateOfBirth\"]
    p         


        
5条回答
  •  有刺的猬
    2021-01-23 11:01

    This is definitely doable without instantiating a Person object. You'll want to use Reflection to access the attribute, specifically the GetCustomAttributes method.

    Here's an article for reference.

    Your end result may end up looking something like this:

    System.Attribute[] attrs = System.Attribute.GetCustomAttributes(typeof(Person));  // Reflection.
    

提交回复
热议问题