Question

Comment puis-je utiliser un initialiseur d'objet avec une implémentation d'interface explicite en C #?

public interface IType
{
  string Property1 { get; set; }
}

public class Type1 : IType
{
  string IType.Property1 { get; set; }
}

...

//doesn't work
var v = new Type1 { IType.Property1 = "myString" };
Était-ce utile?

La solution

Vous ne pouvez pas. La seule façon d'accéder à une mise en œuvre explicite à travers une distribution à l'interface. ((IType)v).Property1 = "blah";

Vous pourriez théoriquement envelopper un proxy autour de la propriété, puis utiliser la propriété proxy dans l'initialisation. (Le proxy utilise la fonte à l'interface.)

class Program
{
    static void Main()
    {
        Foo foo = new Foo() { ProxyBar = "Blah" };
    }
}

class Foo : IFoo
{
    string IFoo.Bar { get; set; }

    public string ProxyBar
    {
        set { (this as IFoo).Bar = value; }
    }
}

interface IFoo
{
    string Bar { get; set; }
}

Autres conseils

Méthodes d'interface explicites / propriétés sont privées (ce qui est la raison pour laquelle ils ne peuvent pas avoir un modificateur d'accès: il serait toujours private et serait donc redondant *). Donc, vous ne pouvez pas leur attribuer de l'extérieur. Vous pourriez aussi bien demander: comment puis-je attribuer à des propriétés privées / champs de code externe

(* Bien pourquoi ils ne faisaient pas le même choix avec public static implicit operator est un autre mystère!)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top