如何包装基类的静态属性以便它们返回子类对象?

时间:2012-07-12 22:19:46

标签: c# .net inheritance static

说我有这样的代码:

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属性。它有一个私人二传手。所以我不能在子类中设置它。可以设置的唯一方法是通过预设属性。

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

2 个答案:

答案 0 :(得分: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类。

答案 1 :(得分: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);
    }
}

将写“继承”。