【问题标题】:Need explanation about my Interface code需要解释我的接口代码
【发布时间】:2015-08-29 15:38:17
【问题描述】:

谁能解释下面的代码,谁能用下面的代码sn-ps给出一些实时的解释

public interface roman
{
    roman this[string name] { get; }
}

public class notempty : roman
{
    public string Color{ get; set; }

    public roman this[string name]
    {
        get { return new notempty() { Color= "Value1" }; }
    }
}

【问题讨论】:

  • 如果你能解释一下你懂哪些不懂的地方会有所帮助
  • 实时解释?你想电话会议吗?
  • 我建议你阅读这篇文章.. stackoverflow.com/questions/2697783/…
  • 我可以告诉你,该 sn-p 中的大部分内容不符合命名约定。类名、构造函数、方法和公共属性必须使用 PascalCasing。除此之外,您还有一个派生自接口的类,这是非常基本的东西。
  • @MatteoMosca 必须是一个非常强烈的词。

标签: c# interface


【解决方案1】:
public interface roman // there is an interface called "roman", accessible to all
{
    // all implementations of "roman" must have an "indexer" that takes a string
    // and returns another "roman" instance (it is not required to offer a "set")
    // typical usage:
    //     roman obj = ...
    //     roman anotherObj = obj["abc"];
    roman this[string name] { get; }
}

public class notempty : roman // there is a class "notempty", accessible to all,
{                             // which implements the "roman" interface

    // no constructors are declared, so there is a default public parameterless
    // constructor which simply calls the parameterless base-constructor

    // any instance of "notempty" has a string property called "Color" which can
    // be both read (get) and written (set) by any callers; there
    // is also a *field* for this, but the compiler is handling that for us
    public string Color{ get; set; }

    // there is an indexer that takes a string and returns a "roman"; since
    // there is no *explicit* implementation, this will also be used to satisfy
    // the "roman" indexer, aka "implicit interface implementation"
    public roman this[string name]
    {
        // when the indexer is invoked, the string parameter is disregarded; a
        // new "notempty" instance is created via the parameterless constructor,
        // and the "Color" property is assigned the string "Value1"; this is then
        // returned as "roman", which it is known to implement
        get { return new notempty() { Color= "Value1" }; }
    }
}

【讨论】:

    【解决方案2】:

    接口 roman 定义所有实现都应该有一个索引器 this[string name] 返回一个 roman 实例。

    退房:

    C# Station Tutorial - Interfaces

    C# Station Tutorial - Indexers

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 2021-07-03
      • 1970-01-01
      • 2020-02-20
      • 1970-01-01
      相关资源
      最近更新 更多