1

假设我有这样的代码:

public class Base  // I cannot change this class
{
    public string Something { get; private set; }
    public string Otherthing { get; set; }

    public static Base StaticPreSet
    {
        get { return new Base { Something = "Some", Otherthing = "Other"}; }
    }

    public static Base StaticPreSet2
    {
        get { return new Base { Something = "Some 2", Otherthing = "Other 2"}; }
    }
}

public class SubClass : Base  // I can change this class all I want.
{
    public string MoreData { get; set; }

    // How can I wrap the PreSets here so that they return SubClass objects?
    // Something like this:
    public static SubClass MyWrappedPreset 
    {
       get
       {
          // Code here to call the base preset and then use it as the 
          // base of my SubClass instance.
       }
    }
}

使这变得复杂的是Something 属性。它有一个私人二传手。所以我不能在子类中设置它。可以设置它的唯一方法是通过预设属性。

有没有办法将 StaticPreSet 属性包装在我的子类中,以便它返回子类类型的对象?

4

2 回答 2

2

// 我不能改变这个基类。

鉴于您无法更改基类,因此无法使其更改行为(即:在运行时返回不同的类)。

如果您可以影响基类静态方法的设计,您可以重新设计它,使其足够灵活以提供此功能。但是,如果不更改它,这将行不通。


编辑以响应编辑:

您可以创建一个新的静态方法来执行您所显示的操作,如下所示:

public static SubClass MyWrappedPreset 
{
   get
   {
      // Code here to call the base preset and then use it as the 
      // base of my SubClass instance.
       Base baseInstance = Base.StaticPreSet;
       SubClass sc = new SubClass(baseInstance); // Create a new instance from your base class
       return sc;
   }
}

但是,这提供了一个全新的、不相关的属性——您必须通过SubClass.MyWrappedPreset而不是Base类来访问它。

于 2012-07-12T22:32:52.280 回答
0

类中的静态字段“与它无关”。
基本上,除了对私有静态字段的访问之外,id 放在哪个类中并不重要——它们的行为相同。
如果您继承一个类,并在基类上声明另一个与静态字段同名的静态字段,您将简单地“隐藏”它。给你的例子:

using System;
public class Base  // I cannot change this class
{
    public string Something { get; set; }
    public string Otherthing { get; set; }

    public static Base StaticPreSet
    {
        get { return new Base { Something = "Some", Otherthing = "Other"}; }
    }

    public static Base StaticPreSet2
    {
        get { return new Base { Something = "Some 2", Otherthing = "Other 2"}; }
    }
}

public class SubClass : Base  // I can change this class all I want.
{
    public string MoreData { get; set; }

    public static SubClass StaticPreSet2
    { 
        get { return new SubClass { Something = "inherited", Otherthing=""}; }
    }
}
public class Test
{
    public static void Main()
    {
    Console.WriteLine(SubClass.StaticPreSet2.Something);
    }
}

会写“继承”。

于 2012-07-12T22:37:28.833 回答