.Net 4.0 Optimized code for refactoring existing “if” conditions and “is” operator

后端 未结 7 776
遥遥无期
遥遥无期 2021-01-06 18:02

I have following C# code. It works fine; but the GetDestination() method is cluttered with multiple if conditions by using is operator.

In

7条回答
  •  太阳男子
    2021-01-06 18:33

    you can either use an interface definition or an abstract method / property

    with interface:

    public interface IDestinationProvider
    {
        sting Destination { get; }
    }
    
    string GetDestination(Role role)
    {
        var provider = role as IDestinationProvider;
        if (provider != null)
            return provider.Destination;
        return "Default";
    }
    

    with an abstract base class

    abstract class Role 
    { 
        public abstract string GetDestination();
    }
    
    class Manager : Role
    {
        public virtual string GetDestination() { return "ManagerHomeA"; }
    }
    
    string GetDestination(Role role)
    {
        return @"\" + role.GetDestination();
    }
    

    or with attributes:

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
    public class DestinationAttribute : Attribute
    {
        public DestinationAttribute() { this.Path = @"\Home"; }
        public string Path { get; set; }
    }
    
    [Destination(Path = @"\ManagerHome")]
    public class Manager : Role { }
    
    string GetDestination(Role role)
    {
        var destination = role.GetType().GetCustomAttributes(typeof(DestinationAttribute), true).FirstOrDefault();
        if (destination != null)
            return destination.Path;
    
        return @"\Home";
    }
    

提交回复
热议问题