對論壇討論減少switch分支有感,使用特性反射出需要使用的類,論壇討論switch
今天在論壇上面看到問如何減少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(); } }
完成只需要擴充IGetExec介面 然後添加enum即可實現擴充功能
java中的通過反射,怎解決switch分支語句
你是想原廠模式裡面不用判斷產生哪個類的執行個體嗎?
Class clazz = Class.forName(類名/*字串*/);
clazz.newInstance()產生一個類的執行個體 需要類型轉換
這樣就不用switch了
教 AS3 反射的使用,(getDefinitionByName怎替換switch?)
getDefinitionByName()函數 public function getDefinitionByName(name:String):Object 語言版本 : ActionScript 3.0RuntimeVersions: AIR 1.0, Flash Player 9返回 name 參數指定的類的類對象引用。 參數 name:String — 類的名稱。 返回 Object — 返回 name 參數指定的類的類對象引用。
引發 ReferenceError — 不存在具有指定名稱的公用定義。
樣本
以下樣本使用 GetDefinitionByNameExample 類在舞台上建立一個橙色的正方形。這是使用以下步驟完成的: 聲明代表橙色背景顏色和 80 像素大小的變數,這些變數稍後將用於繪製正方形。 在建構函式內,將 Class 類型的變數 ClassReference 賦予 Sprite。 對名為 instance 的 ClassReference 的執行個體進行執行個體化。 由於 instance 按引用是 Sprite 對象,因此可以使用可用於 Sprite 的方法繪製正方形並將其添加到顯示列表。package { import flash.display.DisplayObject; import flash.display.Sprite; import flash.utils.getDefinitionByName; public class GetDefinitionByNameExample extends Sprite { private var bgColor:uint = 0xFFCC00; private var size:uint = 80; public function GetDefinitionByNameExample() { var ClassReference:Class = getDefinitionByName("flash.display.Sprite") as Class; var instance:Object = new ClassReference(); instance.graphics.beginFill(bgColor); instance.graphics.drawRect(0, 0, size, size); instance.graphics.endFill(); addChild(DisplayObject(instance)); } } }