On the Forum today, I asked how to reduce the switch branch.
I thought for myself and thought that using features can directly reduce the switch judgment, so I wrote some
It indicates that the efficiency may not be comparable to that of the switch.
Let's get started.
First set the interface
public interface IGetExec { string GetResult(); }
Then implement
public class GetExec : IGetExec { public string GetResult() { return "get"; } } public class Get1Exec : IGetExec { public string GetResult() { return "get1"; } } public class GetTestExec : IGetExec { public string GetResult() { return "gettest"; } }
Create features
[AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = true)] sealed class TestAttribute : Attribute { private IGetExec ExecObj { get; set; } public TestAttribute(Type t) { this.ExecObj = Activator.CreateInstance(t) as IGetExec; } public string Exec() { return ExecObj.GetResult(); } }
Define an Enum to determine which class to use
public enum TestEnum { [Test(typeof(GetExec))] get, [Test(typeof(Get1Exec))] getTest, [Test(typeof(GetTestExec))] get1 }
Then extend the enum method.
public static class EnumClass { public static string Exec(this TestEnum e) { Type t = e.GetType(); var file = t.GetField(e.ToString()); var att = file.GetCustomAttributes(typeof(TestAttribute), false).Single(); if (att != null) { return (att as TestAttribute).Exec(); } else return null; } }
Last call
public class Program { static void Main(string[] args) { Console.WriteLine(TestEnum.get.Exec()); Console.Read(); } }
You only need to extend the igetexec interface and then add Enum to implement the extension function.
Reduces the perception of the switch branch discussed in the forum, and uses features to reflect the classes to be used