Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 动态字段上无法识别扩展名_C#_Dynamic_Decimal_Extension Methods - Fatal编程技术网

C# 动态字段上无法识别扩展名

C# 动态字段上无法识别扩展名,c#,dynamic,decimal,extension-methods,C#,Dynamic,Decimal,Extension Methods,我在十进制字段上使用了此扩展: public static class Extensions { static System.Globalization.CultureInfo _cultInfo = System.Globalization.CultureInfo.InvariantCulture; public static string ConvertToStringWithPointDecimal(this decimal source) { re

我在十进制字段上使用了此扩展:

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();
}}
ResultToToFordHardDecimal和ResultToForProp1Decimal都返回正确的字符串值,但是当代码命中mySource.prop2.ConvertToStringWithPointDecimal()时,我得到以下错误:“'decimal'不包含'ConvertToStringWithPointDecimal'的定义”,而prop2是十进制类型

有什么想法吗

亲切问候,


Matthijs

扩展方法不适用于动力学

因为C#编译器无法在构建时解析
mySource.prop2
的类型,所以它无法知道它是否可以使用扩展方法

但是,您仍然可以显式调用该方法:

string resultOutOfProp2 = Extensions.ConvertToStringWithPointDecimal(mySource.prop2);
(与任何静态方法一样)


另请参见:Jon Skeet和Eric Lippert的答案。

为什么不直接使用
扩展名。ConvertToString WithPointDecimal(mySource.prop2)
?是的,退出愚蠢不是吗。我只是没想过。(咖啡快喝完了)。但是谢谢你和亚历山德罗·安德里亚的复制品在这里有一个要点…我需要一些额外的咖啡:-)谢谢