문제

When I define an interface that contains a write-only property:

public interface IModuleScreenData
{
    string Name { set; }
}

and attempt to (naively) implement it explicitly with an intention for the property to also have a publicly available getter:

public class ModuleScreen : IModuleScreenData
{
    string IModuleScreenData.Name { get; set; }
}

then I get the following error:

Error 'IModuleScreenData.Name.get' adds an accessor not found in interface member 'IModuleScreenData.Name'

The error is more or less expected, however, after this alternative syntax:

public class ModuleScreen : IModuleScreenData
{
    public string Name { get; IModuleScreenData.set; }
}

has failed to compile, I suppose that what I am trying to do is not really possible. Am I right, or is there some secret sauce syntax after all?

도움이 되었습니까?

해결책

You can do this:

public class ModuleScreen : IModuleScreenData
{
    string IModuleScreenData.Name
    {
        set { Name = value; }
    }

    public string Name { get; private set; }
}

On a side note, I generally wouldn't recommend set-only properties. A method may work better to express the intention.

다른 팁

You can't change the how the interface is implemented in the inheriting class. That is the whole point.. if you need to do something new with a property you could make a new property that references the inherited properties specific implementation. Interfaces are there so you can conform to a specified standard for object inheritance.

UPDATE: On second thought.. you should be able to just do this.... this will compile fine:

public class ModuleScreen : IModuleScreenData
    {
        public string Name { get; set; }
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top