为什么 C#(或 .NET)不允许我们在接口中放置静态/共享方法? [英] Why shouldn't C#(or .NET) allow us to put a static/shared method inside an interface?
问题描述
为什么 C#(或 .NET)不允许我们在接口中放置静态/共享方法?
Why shouldn't C#(or .NET) allow us to put a static/shared method inside an interface?
看似重复来自 这里.但我的想法有点不同,我只想为我的插件(接口)添加一个助手
seemingly duplicate from here. but my idea is a bit different one, I just want to put a helper for my plugins(interface)
C# 至少不应该允许这个想法吗?
shouldn't C# at least allow this idea?
namespace MycComponent
{
public interface ITaskPlugin : ITaskInfo
{
string Description { get; }
string MenuTree { get; }
string MenuCaption { get; }
void ShowTask(Form parentForm);
void ShowTask(Form parentForm, Dictionary<string, object> pkColumns);
ShowTaskNewDelegate ShowTaskNew { set; get; }
ShowTaskOpenDelegate ShowTaskOpen { set; get; }
// would not compile with this:
public static Dictionary<string, ITaskPlugin> GetPlugins(string directory)
{
var l = new Dictionary<string, ITaskPlugin>();
foreach (string file in Directory.GetFiles(directory))
{
var fileInfo = new FileInfo(file);
if (fileInfo.Extension.Equals(".dll"))
{
Assembly asm = Assembly.LoadFile(file);
foreach (Type asmType in asm.GetTypes())
{
if (asmType.GetInterface("MycComponent.ITaskPlugin") != null)
{
var plugIn = (ITaskPlugin)Activator.CreateInstance(asmType);
l.Add(plugIn.TaskName, plugIn);
}
}
}
}
return l;
} // GetPlugins. would not compile inside an interface
}
/* because of the error above, I am compelled to
put the helper method in a new class. a bit overkill when the method should
be closely coupled to what it is implementing */
public static class ITaskPluginHelper
{
public static Dictionary<string, ITaskPlugin> GetPlugins(string directory)
{
var l = new Dictionary<string, ITaskPlugin>();
foreach (string file in Directory.GetFiles(directory))
{
var fileInfo = new FileInfo(file);
if (fileInfo.Extension.Equals(".dll"))
{
Assembly asm = Assembly.LoadFile(file);
foreach (Type asmType in asm.GetTypes())
{
if (asmType.GetInterface("MycComponent.ITaskPlugin") != null)
{
var plugIn = (ITaskPlugin)Activator.CreateInstance(asmType);
l.Add(plugIn.TaskName, plugIn);
}
}
}
}
return l;
} // GetPlugins
} // ITaskPluginHelper
}
推荐答案
接口的概念是代表一个契约,而不是实现.
The idea of an interface is to represent a contract, not implementation.
我不记得 IL 是否真的确实允许在接口中实现静态方法——我偷偷地怀疑它确实如此——但这有点混淆了这个概念.
I can't remember offhand whether IL actually does allow static methods with implementations in interfaces - I've a sneaky suspicion that it does - but that muddies the concept somewhat.
我明白你的意思 - 有时了解哪些与接口相关的辅助方法是有用的(并且扩展方法在那里特别相关),但我个人还是想把它们放在一个单独的类中,只是为了保持思维模型清洁.
I can see your point - it's sometimes useful to know what helper methods are available which are connected with an interface (and extension methods are particularly relevant there) but I would personally want to put those in a separate class anyway, just to keep the mental model clean.
这篇关于为什么 C#(或 .NET)不允许我们在接口中放置静态/共享方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!