简体   繁体   中英

What is the best way to implement dynamic property in a C# object?

I have a number of class objects, each of which needs a URL field which is always formatted in the same way via parameter TypeId , another property of the class.

What is the best way to abstract this as a dynamic property so the URL field is generated based on the TypeId and ItemId properties from the class.

I can think of many ways to do this but wondered what the recommended practice was.

Example below:

public class MyObject
{
    public int Id { get; set; }
    public string URL
    {
        get
        {
            if (TypeId == 3)
            {
                return "/do/this/" + ItemId;
            }
            if (TypeId == 5)
            {
                return "/do/that/" + ItemId;
            }
            return "#";
        }
    }
    public int ItemId { get; set; }
    public int TypeId { get; set; }
}

You could set up a dictionary with all of the known TypeIds and a Func<int, string> to return the URL. You could even make it so new TypeIds and URL-formatting functions could be added at runtime:

private Dictionary<int, Func<int, string>> _urlFormatters;

public string URL
{
    get { return _urlFormatters[TypeId](ItemId); }
}

// In the constructor or some other init area:
{
    _urlFormatters = new Dictionary<int, Func<int, string>>
        {
            { 3, itemId => "/do/this/" + itemId },
            { 5, itemId => "/do/that/" + itemId }
        };
}

You can go a step further and implement it full object:

public abstract class MyObject
{
    public int ItemId { get; set; }
    public virtual string URL { get { return "#"; } }
}
public class MyObjectType3 : MyObject
{
    public override string URL { get { return "/do/this/" + ItemId; } }
}
public class MyObjectType5 : MyObject
{
    public override string URL { get { return "/do/that/" + ItemId; } }
}

It depends if you have a lot of type, if this logic make sense or not.
This is just an other solution, but the one you give looks fine also.

abstract class BaseClass {
    public int ItemId { get; set; }
    public abstract string BaseUrl { get; }
    public string Url {
        get {
            return BaseUrl + ItemId;
        }
    }
}

class Type3 : BaseClass {
    public override string BaseUrl {
        get { return "/do/this/"; }
    }
}

class Type5 : BaseClass {
    public override string BaseUrl {
        get { return "/do/that/"; }
    }
}

您可以在其他类继承的基类中执行此操作...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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