gpt4 book ai didi

c# - 为什么 C#(或 .NET)不允许我们在接口(interface)中放置静态/共享方法?

转载 作者:太空狗 更新时间:2023-10-29 19:52:48 26 4
gpt4 key购买 nike

为什么 C#(或 .NET)不允许我们在接口(interface)中放置静态/共享方法?

似乎与 Why we can not have Shared(static) function/methods in an interface/abstract class? 重复, 但我的想法有点不同,;我只是想为我的插件(接口(interface))添加一个助手

至少 C# 不应该允许这个想法吗?

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
}

最佳答案

接口(interface)的思想是代表契约,而不是实现。

我不记得 IL 是否真的确实允许静态方法在接口(interface)中实现 - 我偷偷怀疑它确实如此 - 但这有点混淆了这个概念。

我明白你的意思 - 有时了解哪些可用的辅助方法与接口(interface)连接是有用的(扩展方法在那里特别相关)但我个人还是想将它们放在一个单独的类中,只是为了保持心智模型清洁。

关于c# - 为什么 C#(或 .NET)不允许我们在接口(interface)中放置静态/共享方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1062468/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com