c# - 如何将 Action<string> 添加到界面?

标签 c# .net

正如问题标题所暗示的,我想添加一个 Action<string>到一个界面。这可能吗?目前它说 Interfaces cannot contain fields

最佳答案

您需要将其添加为属性:

public interface IYourInterface
{
    Action<string> YourAction { get; set; }
}

没有 get/set 它只是一个字段,正如编译器指出的那样,接口(interface)不能包含字段。这确实意味着当您实现此接口(interface)时,您还需要提供实际属性(尽管很明显它可以是一个简单的自动属性):

public class Foo : IYourInterface
{
    public Action<string> YourAction { get; set; }

    // ...
}

鉴于此,您可以使用您的 Action<string>从界面:

IYourInterface iFoo = new Foo();

iFoo.YourAction = s => Console.WriteLine(s);

iFoo.YourAction("Hello World!");

正如 Hans 指出的那样,您可以在界面中仅指示一个 get (或者甚至只是一个 set )如果你愿意的话。这并不意味着类不能 有另一个类,它只是意味着不能通过接口(interface)访问它。例如:

public interface IYourInterface
{
    Action<string> YourAction { get; }
}

public class Foo : IYourInterface
{
    public Action<string> YourAction { get; set; }
}

所以在上面的代码中,您可以访问 YourAction属性仅作为 get通过界面,但你可以setget它来自 Foo类。

关于c# - 如何将 Action<string> 添加到界面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9772005/

相关文章:

c# - 如何配置 log4net 以在 Debug模式下打印到控制台

c# - MVC 3 表单例份验证在 Internet Explorer 中不起作用,不断重定向到登录页面

c# - NHibernate 异常 "Session is closed! Object name: ' ISession'。”

javascript - ASP.NET - jQuery (document).ready() 函数未被触发用于用户控制

c# - 如何清除一个字节中的一个位?

c# - List<T>.Contains 和 T[].Contains 的行为不同

.net - 实现具有最大项目数的 List(Of) 的最佳方法

.net - linq 与 sql(或 .NET 应用程序与 SQL Server Management Studio)

c# - 如何使用 C# 访问共享点数据?

c# - 访问 json 文件中的子字段