标签:特性 反射
今天在论坛上面看到问如何减少switch分支
我自己想了一下,觉得使用特性,可以直接减少switch的判断,于是就写了一些
表示效率可能无法和switch相提并论
下面就开始吧
首先设置接口
public interface IGetExec
{
string GetResult();
}
然后分别实现
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";
}
}创建特性
[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();
}
}定义一个Enum 来判断具体使用哪个类
public enum TestEnum
{
[Test(typeof(GetExec))]
get,
[Test(typeof(Get1Exec))]
getTest,
[Test(typeof(GetTestExec))]
get1
}
然后扩展Enum的方法
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;
}
}public class Program
{
static void Main(string[] args)
{
Console.WriteLine(TestEnum.get.Exec());
Console.Read();
}
}
对论坛讨论减少switch分支有感,使用特性反射出需要使用的类
标签:特性 反射
原文地址:http://blog.csdn.net/qq6648208281/article/details/39464529