Why is an ExpandoObject breaking code that otherwise works just fine?

前端 未结 7 949
感动是毒
感动是毒 2021-02-01 02:12

Here\'s the setup: I have an Open Source project called Massive and I\'m slinging around dynamics as a way of creating SQL on the fly, and dynamic result sets on the fly.

<
7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-01 02:53

    When you pass the dynamic to CreateCommand, the compiler is treating its return type as a dynamic that it has to resolve at runtime. Unfortunately, you're hitting some oddities between that resolver and the C# language. Fortunately, it's easy to work around by removing your use of var forcing the compiler to do what you expect:

    public static dynamic DynamicWeirdness() {
        dynamic ex = new ExpandoObject ();
        ex.Query = "SELECT * FROM Products";
        using (var conn = OpenConnection()) {
            DbCommand cmd = CreateCommand(ex); // <-- DON'T USE VAR
            cmd.Connection = conn;
        }
        Console.WriteLine("It worked!");
        Console.Read();
        return null;
    }
    

    This has been tested on Mono 2.10.5, but I'm sure it works with MS too.

提交回复
热议问题