相关疑难解决方法(0)

使用自动属性显式实现接口

有没有办法使用自动属性显式实现接口?例如,考虑以下代码:

namespace AutoProperties
{
    interface IMyInterface
    {
        bool MyBoolOnlyGet { get; }
    }

    class MyClass : IMyInterface
    {
        static void Main(){}

        public bool MyBoolOnlyGet { get; private set; } // line 1
        //bool IMyInterface.MyBoolOnlyGet { get; private set; } // line 2
    }
}
Run Code Online (Sandbox Code Playgroud)

这段代码编译.但是,如果将第1行替换为第2行,则无法编译.

(这不是我需要让第2行工作 - 我只是好奇.)

c# automatic-properties

14
推荐指数
2
解决办法
3174
查看次数

为构造函数中显式实现的只读接口属性赋值

问题相同,但对于C#7.0而不是6.0:

有没有办法在构造函数中为显式实现的只读(仅限getter)接口属性赋值?或者它仍然是相同的答案,即使用支持领域的解决方案?

例如:

interface IPerson
{
    string Name { get; }
}

class MyPerson : IPerson
{
    string IPerson.Name { get; }

    internal MyPerson(string withName)
    {
        // doesn't work; Property or indexer 'IPerson.Name' 
        // cannot be assigned to --it is read only
        ((IPerson)this).Name = withName; 
    }
}
Run Code Online (Sandbox Code Playgroud)

解决方法:

class MyPerson : IPerson
{
    string _name;
    string IPerson.Name { get { return _name; } }

    internal MyPerson(string withName)
    {
        _name = withName; 
    }
}
Run Code Online (Sandbox Code Playgroud)

.net c# c#-7.0

4
推荐指数
1
解决办法
767
查看次数

只读并在Interface中只写自动属性

我读过自动实现的属性不能只读或只写.它们只能是读写的.

然而,在学习界面时,我遇到了foll.代码,它创建只读/只写和读写类型的自动属性.那可以接受吗?

 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; } 
    } 
Run Code Online (Sandbox Code Playgroud)

c# properties interface

3
推荐指数
1
解决办法
615
查看次数

标签 统计

c# ×3

.net ×1

automatic-properties ×1

c#-7.0 ×1

interface ×1

properties ×1