티스토리 뷰

Language/C#

[C#] Custom Attribute 예제

jhbaek 2018. 5. 15. 21:36

C#은 Custom Attribute를 통해 meta data 형식으로 데이터 관리가 가능하다.

디바이스를 관리하는 IDevice 클래스와 이를 상속 받은 DeviceIPhone. 그리고 이 DeviceIPhone에서 관리하는 각 Device에 대하여

Custom Attribute를 통해 다루어 보자.

 

[SupportVendor("Apple")]
[SupportModel("IPhone8", true)]
[SupportModel("IPhoneX", false)]
class DeviceIPhone : IDevice
{
...
}

우선 위처럼 사용한다. 그러기 위해선 SupportVendor과 SupportModel에 대한 Custom Attribute가 정의돼 있어야 한다.

[AttributeUsage(AttributeTargets.Class)]
public class SupportVendor : Attribute
{
    public string Vendor { get; set; }
    public SupportVendor(string vendor)
    {
        Vendor = vendor;
    }
}

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class SupportModel : Attribute
    {
    public string Model { get; }
    public bool SupportHomeButton { get; }
    public SupportModel(string model, bool supportHomeButton)
    {
        this.Model = model;
        this.SupportHomeButton = supportHomeButton;
    }
}

위와 같이 생겼음.

그리고 이 값을 사용하는 방법은 아래와 같다.

public new static bool IsSupport(string model, string vendor)
{
    // compare Vendor
    var attVendors = (SupportVendor[])typeof(DeviceIPhone).GetCustomAttributes(typeof(SupportVendor), false);
    if (attVendors.Length <= 0)
        return false;

    if (vendor != attVendors[0].Vendor)
        return false;

    // compare Model
    var attModels = (SupportModel[])typeof(DeviceIPhone).GetCustomAttributes(typeof(SupportModel), false);
    foreach(var att in attModels)
    {
        if (att.Model == model)
            return true;
    }

    return false;
}

이런식으로 접근해서 쓴다.

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함