2017-03-08 5 views
-1

私は、第三者からフィルタリング情報を取得し、その情報をフィルタリングするために使用するExcelエクスポートクラスを持っています。フィルタリング情報は、 "equal"、 "greatherthan"などの文字列で提供されます。これらのフィルタリングタイプをC#コードに変換できる再利用可能なコードを生成する最適な方法は何ですか。C#では、型のような演算子を渡すか返すことが可能です

私はそれを演算子に変換して返すのが良いかもしれないと思っていました。しかし、これが可能かどうかは分かりません。どう思いますか?

+0

参照[デザインパターン](HTTPS://en.wikipedia .org/wiki/Software_design_pattern#Behavioral_patterns)。関心のあるものは、メディエータパターンまたはプロキシパターンです。 – Igor

+1

私は戦略パターンを考えていました。 – Amy

+2

あなたが記述する演算子(>、!= etc)は、同じ型の2つの引数をとり、boolを返す関数です。したがって、Func デリゲートとして格納することができます(Tは引数の型です)。 – Evk

答えて

0

これを試してみてください:

public class ExcelFiltersManager 
{ 
    public static class ExcelFilters 
    { 
     public const string Equal = "equals"; 
     public const string GreaterThen = "greaterthan"; 

     // complete here the other operators. 
    } 

    static class Operators 
    { 
     // C# compiler converts overloaded operators to functions with name op_XXXX where XXXX is the opration 

     public const string Equality = "op_Equality"; 
     public const string InEquality = "op_Inequality"; 
     public const string LessThan = "op_LessThan"; 
     public const string GreaterThan = "op_GreaterThan"; 
     public const string LessThanOrEqual = "op_LessThanOrEqual"; 
     public const string GreaterThanOrEqual = "op_GreaterThanOrEqual"; 
    } 

    public bool GetOperatorBooleanResult<T>(string excelFilter, T value1, T value2) 
    { 
     MethodInfo mi = typeof(T).GetMethod(GetOperatorCompileName(excelFilter), BindingFlags.Static | BindingFlags.Public); 
     return (bool)mi.Invoke(null, new object[] { value1, value2 }); 
    } 

    private string GetOperatorCompileName(string excelFilter) 
    { 
     string operatorCompileName = string.Empty; 

     switch (excelFilter) 
     { 
      case ExcelFilters.Equal: 
       operatorCompileName = Operators.Equality; 
       break; 
      case ExcelFilters.GreaterThen: 
       operatorCompileName = Operators.GreaterThan; 
       break; 

       // continue here the mapping with the rest of operators 
     } 

     return operatorCompileName; 
    } 
} 

、あなたのコード内で使用すると、フィルタの結果を取得するには、次を使用することができます。

decimal value1 = 5; 
decimal value2 = 10; 

bool result = GetOperatorBooleanResult(ExcelFilters.GreaterThen, value1, value2); 
+0

Hmm。これは興味深いことですが、私は内部的に演算子が文字列名を持っているのか分かりませんでした。他の提案のいくつかを見てみましょうが、これは有望です。ありがとう。 –

関連する問題