【问题标题】:How should I implement interface composition?我应该如何实现接口组合?
【发布时间】:2011-11-27 13:39:53
【问题描述】:

我有这种情况:

public interface IHasValue<T>
    {
        T Value { get; set; }
    }

public interface IClickable
    {
        void SubscribeOnClick(EventHandler click);
    }

public interface ILoginView : IView
    {
        IHasValue<string> Username { get; }
        IHasValue<string> Password { get; }
        IClickable Login { get; }
        IClickable Cancel { get; }
    }

public partial class LoginVIew : Form, ILoginView
    {
        public LoginVIew()
        {
            InitializeComponent();
        }

        #region ILoginView Members

        public IHasValue<string> Username
        {
            get { ?? }
        }

        public IHasValue<string> Password
        {
            get { ?? }
        }

        public IClickable Login
        {
            get { ?? }
        }

        public IClickable Cancel
        {
            get { ?? }
        }

        #endregion
    }

我应该如何实现这个?我不知道。

【问题讨论】:

  • 有代码?说真的,我也不知道。能具体点吗?
  • 嗯,我希望是否有某种方法可以创建实现这些接口的内部类对象。喜欢在这个get部分提供一些方法来实现特定的接口。

标签: c# .net interface composition


【解决方案1】:

您需要实现IHasValue&lt;T&gt; 和IClickable 才能创建ILoginView 的实现(因为您需要能够在ILoginView 中创建实现这些接口的对象实例成员。

 public class StringValue : IHasValue<string>
 {
     public string Value { get; set; }
 }

 public interface LoginClickable : IClickable
 {
     public void SubscribeOnClick(EventHandler click)
     {
          // do something to login
     }
 } 

 public interface CancelClickable : IClickable
 {
     public void SubscribeOnClick(EventHandler click)
     {
          // do something to cancel
     }
 } 

...

    public IHasValue<string> Username
    {
        get { return new StringValue { Value = "Username" }; }
    }

    public IHasValue<string> Password
    {
         get { return new StringValue { Value = "Password" }; }
    }

    public IClickable Login
    {
        get { return new LoginClickable(); }
    }

    public IClickable Cancel
    {
        get { return new CancelClickable(); }
    }

【讨论】:

  • 是否需要关闭StringValue?用class Value&lt;T&gt; : IHasValue&lt;T&gt;不行吗?
  • 是的,好建议。这取决于OP的要求。也许那里会有更多的逻辑。
  • 在财产方面没有其他更优雅的方法吗?
  • 好吧,为了实现一个接口,你需要一个类。
  • 啊,是的。你的权利。我只是有点困惑。我只需要使用我的常规控件来实现这些接口并提供所需的方法。
猜你喜欢
  • 1970-01-01
  • 2016-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多