0

基本プロパティ セッターを設定できない特定の基本型の静的ヘルパー クローン メソッドがあります。

public static T Clone<T>(this T source, DomainKey cloneKey)
    where T : DomainObjectWithKey
{
    T clone = source.Clone(); // binary formatter returns object of type T
    clone.Key = cloneKey; // this does not compile
    return (T)clone;
}

public class DomainObjectWithKey
{
    public DomainKey Key { get; protected set; }

別の解決策は、クラス自体の中に Clone メソッドを配置することでした。これにより、保護されたセッターを使用できるようになりました。ただし、派生オブジェクトから Clone を呼び出すときに指定する必要がありますが、これは無意味に思えました。

したがって、私の質問は、静的メソッドから保護されたセッター メソッドを呼び出すことができないのはカプセル化によるものですか?

代替ソリューションの例ですが、なぜタイプを指定する必要があるのですか?

category.Clone<Category>(otherCategory.Key); // why do I have to specify <Category> here?

public class Category : DomainObjectWithKey
{
    public long CategoryId { get { return ((IdDomainKey)Key).Id; } }

    public Category(long categoryId)
    {
        Key = new IdDomainKey(categoryId);
    }
}

解決

パブリック プロパティを持つことになったので、キーは派生クラスのインスタンスからアクセスできますが、静的ヘルパー メソッドがプロパティを設定できるセッターの内部で保護されています。

public class DomainObjectWithKey
{
    public DomainKey Key { get; protected internal set; }
4

1 に答える 1

2

protectedのサブクラスから見えることを意味しDomainObjectWithKeyます。あなたのCloneメソッドは の外にあるようですDomainObjectWithKey

多分あなたは探していinternalますか?internal同じ DLL 内からメンバーにアクセスできます。

于 2012-10-22T18:25:10.910 に答える