c# - 只读和只写接口(interface)中的自动属性

标签 c# properties interface

我读到自动实现的属性不能只读或只写。它们只能是可读写的。

但是,在学习界面时,我遇到了很多问题。代码,它创建一个只读/只写和读写类型的自动属性。这是可以接受的吗?

 public interface IPointy 
    {   
    // A read-write property in an interface would look like: 
    // retType PropName { get; set; }   
    //  while a write-only property in an interface would be:   
    // retType PropName { set; }  
      byte Points { get; } 
    } 

最佳答案

这不是自动实现的。接口(interface)不包含实现。

声明接口(interface)IPointy 需要byte 类型的属性,名为Points,带有公共(public)getter.


只要有public getter,你可以用任何必要的方式实现接口(interface);是否通过自动属性:

public class Foo: IPointy
{
    public byte Points {get; set;}
}

注意 setter 仍然可以是私有(private)的:

public class Bar: IPointy
{
    public byte Points {get; private set;}
}

或者,您可以显式编写一个 getter:

public class Baz: IPointy
{
    private byte _points;

    public byte Points
    {
        get { return _points; }
    }
}

关于c# - 只读和只写接口(interface)中的自动属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30022654/

相关文章:

java - 我可以在 Java 中重命名已实现的方法吗?

java - 包含具有相同签名的方法的多个接口(interface)

c# - 使用 NEST for ElasticSearch 获取空结果

c# - 有什么方法可以在复杂类型上使用 OData $orderby 吗?

c# - Xamarin Forms - 更新标签值

java - .properties 文件正在被覆盖。如何克服呢?

c# - 在方法中访问属性时使用私有(private)或公共(public)属性成员?

objective-c - iOS 获取属性类

c# - 在 C# 中将数据集发送到没有数据库连接的 Crystal 报表

c# - C#中的接口(interface)冲突解决