【问题标题】:Optional voids in interface C#接口 C# 中的可选空格
【发布时间】:2012-08-24 10:14:27
【问题描述】:

你好,我做了一个插件界面,看起来像这样

 public  interface IPluginInterface :IEquatable<IPluginInterface>
{
    string Maker { get; }
    string Version { get; }  
    void Do();
    void Do_two();
}

我试过了,但还没有找到任何方法使字符串 Maker 和 Version 可选, 我想我必须设置一个布尔等于,但不知道如何。 谢谢你的帮助

【问题讨论】:

    标签: c# plugins interface


    【解决方案1】:

    如果你在接口中声明了它们,它们必须被实现。

    您不能在接口上声明可选成员。

    您有多种选择:

    • 将接口分成两部分。只实施您需要的。
    • 实现一个抽象类,其中“可选”成员为空且非抽象。

    【讨论】:

      【解决方案2】:

      您不能将任何接口方法标记为可选 - 要么实现整个接口,要么根本不实现它!

      您可以考虑将此接口拆分为两个不同的接口。

      【讨论】:

        【解决方案3】:

        把界面分成几个:

        public interface IPluginInterface : IEquatable<IPluginInterface>
        {
            string Maker { get; }
            string Version { get; }  
        }
        
        public interface IPluginWithOptionA : IPluginInterface
        {
            void Do();
        }
        
        public interface IPluginWithOptionB : IPluginInterface
        {
            void Do_two();
        }
        

        您可以实现一个或多个接口

        public class MyPlugin : IPluginWithOptionA, IPluginWithOptionB
        {
            public bool Equals(IPluginInterface other)
            {
                throw new NotImplementedException();
            }
        
            public string Maker
            {
                get { throw new NotImplementedException(); }
            }
        
            public string Version
            {
                get { throw new NotImplementedException(); }
            }
        
            public void Do_two()
            {
                throw new NotImplementedException();
            }
        
            public void Do()
            {
                throw new NotImplementedException();
            }
        }
        

        【讨论】:

          【解决方案4】:

          如果你想让这个方法是可选的,那么接口是错误的。但是您可以将它们放入抽象基类中。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2015-02-15
            • 2011-07-13
            • 2011-02-03
            • 2020-07-08
            • 1970-01-01
            • 2020-02-07
            • 2011-09-26
            相关资源
            最近更新 更多