相关疑难解决方法(0)

扩展方法和动态对象

我将把我的问题总结为以下代码片段.

List<int> list = new List<int>() { 5, 56, 2, 4, 63, 2 };
Console.WriteLine(list.First());
Run Code Online (Sandbox Code Playgroud)

上面的代码工作正常.

现在我尝试了以下内容

dynamic dList = list;
 Console.WriteLine(dList.First());
Run Code Online (Sandbox Code Playgroud)

但是我得到了RuntimeBinderException.为什么会这样?

c# dynamic c#-4.0

93
推荐指数
3
解决办法
2万
查看次数

C#动态可能存在错误吗?

我遇到过在C#中使用动态变量的问题.这是在编写NancyFx路由模块时出现的,但我已将问题归结为下面的示例.虽然我在原始代码中收到了一个不同的例外,但示例代码仍然会抛出一个我认为是错误的异常.有没有人看到这里发生了什么,或有其他人遇到类似的问题?

请注意,以下帖子可能是相关的: StackOverflowException通过动态访问泛型类型的成员时:.NET/C#framework bug? System.Dynamic错误?

代码:

class Program
{
    static void Main(string[] args)
    {
        var dictionary = new Dictionary<string, object>();
        dictionary.Add("number", 12);
        var result = MethodUsesExplicitDeclaration(dictionary);
        var result2 = MethodUsesImplicitDeclaration(dictionary);
    }

    static dynamic MethodUsesExplicitDeclaration(dynamic reallyDictionary)
    {
        // this works, ostensibly because the local variable is explicitly declared
        IDictionary<string, object> dictionary = CastDictionary(reallyDictionary);
        return dictionary.Get<int>("number");
    }

    static dynamic MethodUsesImplicitDeclaration(dynamic reallyDictionary)
    {
        // this throws an exception, and the only difference is 
        // that the variable declaration is implicit
        var dictionary = …
Run Code Online (Sandbox Code Playgroud)

c# dynamic

5
推荐指数
1
解决办法
2283
查看次数

标签 统计

c# ×2

dynamic ×2

c#-4.0 ×1