编译器服务使用ExpandoObject时缺少信息

时间:2014-04-03 19:17:47

标签: c# .net .net-4.5

问题似乎与传递给方法的Expando对象有关。如果我传入ExpandoObject,则应自动生成的编译器服务信息为空。如果你在方法中没有使用ExpandoObject,那么信息就可以很好地传递。

我创建了一个快速测试用例:

public class TestClass
    {
        public void TestWithClass(object SomeClass, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0)
        {
            Console.WriteLine(memberName); // Compiler Services information prints out just fine.
        }

        public void TestWithExpando(ExpandoObject xPando, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0)
        {
            Console.WriteLine(memberName); // Compiler Services information is blank
        }

        public void RunTest()
        {
            //This test case works fine.
            var jnk = new Junk {Test = "TEST DATA"};
            TestWithClass(jnk);


            //This test case fails to print the Compiler Services information.
            dynamic xp = new ExpandoObject();
            xp.Test = "TEST DATA";

            TestWithExpando(xp);
        }

        public class Junk
        {
            public string Test { get; set; }
        }
    }

1 个答案:

答案 0 :(得分:1)

编译器服务信息由编译器完成,问题不是ExpandoObject,它是dynamic关键字,因为你正在延迟调用,因此它由DLR而不是编译器处理。首先投射到object将解决此问题。

TestWithExpando((object)xp);