0

10 進数フィールドでこの拡張機能を使用しました。

public static class Extensions
{
    static System.Globalization.CultureInfo _cultInfo = System.Globalization.CultureInfo.InvariantCulture;
    public static string ConvertToStringWithPointDecimal(this decimal source)
    {
        return source.ToString(_cultInfo);
    }
}

しかし、小数を含むクラス型を含む動的パラメーターがある場合、それらのフィールドで拡張機能を使用できません。

テスト設定:

public class TestDecimalPropClass
{
    public decimal prop1 { get; set; }
    public decimal prop2 { get; set; }
}

private void TryExtensionOnDynamicButton(object sender, EventArgs e)
{
    TestDecimalPropClass _testDecimalPropClass = new TestDecimalPropClass { prop1 = 98765.432M, prop2 = 159.753M };
    TestExtension(_testDecimalPropClass);
}

private void TestExtension(dynamic mySource)
{
    decimal hardDecimal = 123456.789M;
    string resultOutOfHardDecimal = hardDecimal.ConvertToStringWithPointDecimal();

    decimal prop1Decimal = mySource.prop1;
    string resultOutOfProp1Decimal = prop1Decimal.ConvertToStringWithPointDecimal();

    string resultOutOfProp2 = mySource.prop2.ConvertToStringWithPointDecimal();
}}

resultOutOfHardDecimal と resultOutOfProp1Decimal の両方が正しい文字列値を返しますが、コードが mySource.prop2.ConvertToStringWithPointDecimal() にヒットすると、「'decimal' には 'ConvertToStringWithPointDecimal' の定義が含まれていません」というエラーが表示されますが、prop2 は 10 進数型です。

何かご意見は?

敬具、

マティス

4

1 に答える 1

2

拡張メソッドはダイナミクスでは機能しません。

C# コンパイラはmySource.prop2ビルド時に の型を解決できないため、拡張メソッドを使用できることを認識できません。

ただし、メソッドを明示的に呼び出すことはできます。

string resultOutOfProp2 = Extensions.ConvertToStringWithPointDecimal(mySource.prop2);

(静的メソッドと同様)

参照: Jon Skeet と Eric Lippert からの回答を含む拡張メソッドと動的オブジェクト。

于 2013-09-04T11:02:57.230 に答える