1

Func<> は、別のメソッド内で使用される戻り値を持つメソッドを渡すために使用されることを知っています。Action<> は、別のメソッド内で使用される戻り値を持たないメソッドを渡すために使用されることを知っています。get/set を別のメソッド内で使用できるように、プロパティを渡す方法はありますか?

たとえば、Func<> を使用するメソッドは次のとおりです。

public bool RangeCheck (int minVal, int maxVal, Func<< int, int >> someMethod)  
{  
    bool retval = true;  
    try  
    {  
        for (int count = min; count <= max; count++)  
        {  
            int hello = someMethod(count);  
        }  
    }  
    catch  
    {  
        retval = false;  
    }  
    return retval;  
}  

私が探しているのは次のようなものです:

public bool RangeCheck(int min, int max, Prop<< int >> someProperty)  
{  
    bool retval = true;  
    try  
    {  
        for (int count = min; count <= max; count++)  
        {  
            someProperty = count;  
        }  
    }  
    catch  
    {  
        retval = false;  
    }  
    return retval;  
}  

このようなものはありますか?何も見つかりません。これは非常に便利です。ありがとう。

4

4 に答える 4

6

ラムダをラッパーとして使用できますか?

MyClass myClass = new MyClass();

bool val = RangeCheck(0, 10, () => myClass.MyProperty);

両方を行う場合は、set 用と get 用の 2 つのラムダを作成します。

bool val = RangeCheck(0, 10, () => myClass.MyProperty, (y) => myClass.MyProperty = y);

私の構文はおそらくオフですが、これでアイデアが得られると思います。

于 2012-10-24T20:22:40.763 に答える
3

私が知っていることではありません。リフレクションを使用して、値を取得するプロパティの対応する PropertyInfo オブジェクトとともにオブジェクトを渡すことができます。次に、PropertyInfo の SetValue 関数を呼び出して値を割り当てます (もちろん、読み取り/書き込み可能であると仮定します)。

    public void SetMyIntValue()
    {
        SetPropertyValue(this, this.GetType().GetProperty("MyInt"));
    }

    public int MyInt { get; set; }

    public void SetPropertyValue(object obj, PropertyInfo pInfo)
    {
        pInfo.SetValue(obj, 5);
    }
于 2012-10-24T20:25:09.640 に答える
1

単にそれをref議論にしないのはなぜですか?

public bool RangeCheck(int min, int max, ref int someProperty)

somePropertyメソッド内での値を設定できるようになりました。

そして、次のように呼び出します。

RangeCheck(min, max, ref myProperty);
于 2012-10-24T20:36:22.113 に答える
0

Funcこのようなものを使用できますFunc<int, T>

void Main()
{
    var sc = new SimpleClass();
    var result = RangeCheck(0, 10, x => sc.Value = x );
    System.Console.WriteLine(result);
    System.Console.WriteLine(sc.Value);
}

public class SimpleClass
{
    public int Value { get; set; }
}

public bool RangeCheck<T>(int minVal, int maxVal, Func<int, T> someMethod)   
{   
    bool retval = true;   
    try   
    {   
        for (int count = minVal; count <= maxVal; count++)   
        {
            //someMethod(count); //is not a range check,
            //Did you mean
            someMethod(count - minValue);
        }   
    }   
    catch   
    {   
        retval = false;   
    }   
    return retval;   
}
于 2012-10-24T20:44:42.350 に答える