分配给接口阵列initializator编译但为什么呢? [英] Assign to interface array initializator compiles but why?

查看:224
本文介绍了分配给接口阵列initializator编译但为什么呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我想这将是整齐进行匿名对象,它是一些接口的类型,我看到的,这样我不是唯一的一个。



之前,我开始检查出发生了什么,我写类似下面的一些代码。
。要我游编译它,我使用的.NET Framework 4,我知道有没有办法做到匿名对象实现接口,但是我还没有看到VS有关此代码的投诉。



更妙的是,当我把牙套智能感知是找到我的界面的财产,就像它是有效的代码。



这是为什么一块编译和运行时,它给空引用异常?

 命名空间测试
{
类节目
{
静态无效的主要(字串[] args)
{$ b $提单持有人持有人=新持有{someInterface = {属性= 1}};
Console.WriteLine(holder.someInterface.Property);
}
}

类持有人
{
公共ISomeInterface someInterface {搞定;设置;}
}

接口ISomeInterface
{
int属性{搞定;组; }
}
}


解决方案

 持有人持有人=新持有{someInterface = {属性= 1}}; //<  - 注意你错过了新的关键字

上面的一行等于

 持有人临时=新持有人() ; 
temp.someInterface.Property = 1;
座架=温度; //< - 在这里等你拿空引用异常someInterface为空。

这应该是这样

 持有人持有人=新持有{someInterface =新SomeClass的(){属性= 1}}; //<  - 注意,这里新的关键字

请注意:你的代码永远不会推出匿名类型这是一个对象初始化



当您使用ObjectInitializer语法关键字就意味着你的设置的东西,当你使用ObjectInitializer语法,而不新的关键字就意味着你的阅读的东西。


Today I was thinking it would be neat to make anonymous object which is type of some interface, and I have seen on SO that I am not only one.

Before I started checking out what happens I wrote some code like the one below. To my amusement it compiled, I am using .net framework 4 and I know there is no way to do anonymous objects implement interface, but I have not seen complaint from VS about this code.

Even better when I put braces intelisense is finding "Property" of my interface, just like it would be valid code.

Why is this piece compiling and when ran it is giving null reference exception?

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            Holder holder = new Holder { someInterface = { Property = 1 } };
            Console.WriteLine(holder.someInterface.Property);
        }
    }

    class Holder
    {
        public ISomeInterface someInterface{get; set;}
    }

    interface ISomeInterface
    {
        int Property { get; set; }
    }
}

解决方案

Holder holder = new Holder { someInterface = { Property = 1 } };//<--Note you missed new keyword

Above line is equal to

Holder temp = new Holder();
temp.someInterface.Property = 1;
Holder holder = temp;// <--Here someInterface is null so you get null reference exception. 

This should be something like

Holder holder = new Holder { someInterface = new SomeClass(){ Property = 1 } };//<--Note the new keyword here

Note: Your code never introduced "Anonymous Type" It is an "Object Initializer".

When you use ObjectInitializer syntax with new keyword it means you're setting something, when you use ObjectInitializer syntax without new keyword it means you're reading something.

这篇关于分配给接口阵列initializator编译但为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆