2015-05-26 158 views
0

我正在學習C#,我不確定如何編程以下問題。我需要創建一個能夠評估表達式的類。例如評估表達式通用C#評估條件多態性

  • 檢查兩個對象/字符串彼此相等
  • 比較兩個數字。

僅供對象和字符串的操作==!=被允許,但對數字的附加操作><>=<=是允許的。

現在我想知道下面的實現在C#中是否可行?我用一個構造函數和一個執行函數創建了一個接口。構造函數設置變量,並且Execute函數必須由其固有的類重寫。

請注意,我的編程/語法可能是不正確的......

我有以下的通用接口。

public class ICondition<T> 
{ 
    private T lhs; 
    private T rhs; 
    private string mode; 

    public void Condition(T lhs, string mode, T rhs) 
    { 
     this.lhs = lhs; 
     this.rhs = rhs; 
     this.mode = mode; 
    } 

    public bool Execute() 
    { 
     throw new System.NotImplementedException(); 
    } 
} 

讓另一個類從這個

public class Condition : Condition<string,object> 
{  
    public override bool Execute() 
    { 
     switch(this.mode) 
     { 
      case "==": 
       return lhs == rhs; 
      case "!=": 
       return lhs != rhs; 
      default: 
       throw new ArgumentException("Mode '" + mode + "' does not exists"); 
     } 
    } 
} 

public class Condition : Condition<uint16,uint32,uint64,int16,int32,int64,double,float> 
{  
    public override bool Execute() 
    { 
     switch(this.mode) 
     { 
      case "==": 
       return lhs == rhs; 
      case "!=": 
       return lhs != rhs; 
      case ">=": 
       return lhs >= rhs; 
      case "<=": 
       return lhs <= rhs; 
      case ">": 
       return lhs > rhs; 
      case "<": 
       return lhs < rhs; 
      default: 
       throw new ArgumentException("Mode '" + mode + "' does not exists");  
     } 
    } 
} 

獲得從動地我能叫

Cond1 = Condition('test','==','test'); 
Cond2 = Condition(12,'>',13); 
Cond3 = Condition(14,'<',13.6); 
result1 = Cond1.Execute(); 
result2 = Cond2.Execute(); 
result3 = Cond3.Execute(); 
+1

對於對象和字符串,不要使用==和!=使用t他如下: string a =「hello」; string b =「world」; bool blnEquals = a.Equals(b); http://forums.asp.net/t/1511559.aspx?What+is+the+difference+between+a+Equals+b+and+a+b+ – mac

+0

@mac,謝謝你我會把它帶入帳戶。 –

回答

1

我勸你有一個像這樣的東西一般:

public interface ICondition 
{ 
    bool IsTrue(); 
} 

public class Condition<T> : ICondition 
{ 
    T _param1; 
    T _param2; 
    Func<T,T,bool> _predicate; 

    public Condition<T>(T param1, T param2, Func<T,T,bool> predicate) 
    { 
    _param1 = param1; 
    _param2 = param2; 
    _predicate = predicate; 
    } 

    public bool IsTrue(){ return _predicate(_param1,_param2);} 
} 

public static void Test() 
{ 
    var x = 2; 
    var y = 5; 
    var foo = "foo"; 
    var bar = "bar";  
    var conditions = new List<ICondition> 
    { 
    new Condition(x,y, (x,y) => y % x == 0), 
    new Condition(foo,bar, (f,b) => f.Length == b.Length) 
    } 

    foreach(var condition in conditions) 
    { 
    Console.WriteLine(condition.IsTrue()); 
    } 
}