包含对数据的引用的接口

时间:2016-03-14 17:39:27

标签: c# .net interface

我刚刚了解到,在C#中,您可以从技术上将数据存储在界面中。请参阅以下示例。使用此示例接口和类:

public interface IInterface
{
    int id { get; set; }
}

public class ExampleClass : IInterface
{
    public int id { get; set; }
}

示例程序。

class Program
{
    static void Main(string[] args)
    {
        var newExample = new exampleClass();
        newExample.id = 5;

        IInterface exInterface = newExample;

        Console.WriteLine(exInterface.id);

        Console.ReadLine();
    }
}

我的输出为5.为什么?我认为Interfaces不存储除结构之外的任何东西。这种间接存储和引用是否有技术术语?这不是很糟糕,因为这个功能有点隐藏吗?我通常不会想到引用接口上的属性来检索实际数据,这就是对象的用途。

如果格式错误或我需要清除任何内容,请告诉我。谢谢!

1 个答案:

答案 0 :(得分:1)

接口不存储任何数据。将接口视为(松散地)描述一个合同,该合同说“任何实现我的类必须提供以下属性/方法”。

此代码

render()

这样做:

  

创建var List = React.createClass({ getInitialState: function () { return { deleted: [] }; }, onDelete: function (id) { this.setState({ deleted: this.state.deleted.concat([id]) }); }, render: function() { var Items = this.props.data .filter(item => this.state.deleted.indexOf(item.id) === -1) .map(item => { return ( <Item key={item.id} id={item.id} onDelete={id => this.onDelete(id)}> {item.text} </Item> ); }); return ( <div className="items"> {Items} </div> ); } }); var Item = React.createClass({ render: function() { return ( <div className="item"> {this.props.children} <button className="delete" onClick={() => this.props.onDelete(this.props.id)}>Delete</button> </div> ); } }); ReactDOM.render( <List data={Array of items} />, document.getElementById('content') ); 的新实例,并将值5分配给    var newExample = new ExampleClass(); newExample.id = 5; 属性。

然而,这段代码

ExampleClass

这样说:

  

id的实例投射(更改)到接口 IInterface exInterface = newExample; 的实例。

这意味着,只要您访问newExample变量,您就只能访问该界面中定义的那些属性/方法(即使您的类可能定义了其他属性/方法)。

您永远不能创建接口的实例。它总是在创建实现该接口的类的实例的上下文中。如果然后将该实例强制转换为接口,那么您实际上使用的是“最小公分母”类型方法,并限制对该接口定义的内容的访问。

相关问题