2014-10-17 101 views
-1

我有一系列不同類的繼承樹。這些類中的每一個都有一些我需要時常訪問的靜態屬性。有時候我需要一個特定類的屬性,有時我需要某個多態實例最終發生的特定類的屬性。可以通過實例和類訪問的可覆蓋屬性

這可能比較容易,比如Java(我認爲)。只需製作一堆靜態字段(可以重寫這些字段嗎?我不確定)。但是在C#中,非靜態字段只能通過實例(自然地)訪問,而靜態字段只能通過它們相應的類訪問(非自然地)。

而且,您不能「超載」,呃,靜態。如果某個類具有靜態和非靜態Foo,則執行instance.Foo將失敗,因爲編譯器不清楚哪個Foo指的是即使不可能指向靜態,因爲它不允許。

好的,我會提供一些代碼。說我有這樣的:

class Base 
{ 
    public static readonly string Property = "Base"; 
} 

class Child1 : Base 
{ 
    public static readonly new string Property = "Child 1"; 
} 

class Child2 : Base 
{ 
    public static readonly new string Property = "Child 2"; 
} 

,然後某處:

public void SomeMethod(Base instance) 
{ 
    System.Console.WriteLine(instance.Property); // This doesn't work. 
} 

而且別的地方:

public void SomeOtherMethod() 
{ 
    System.Console.WriteLine(Child2.Property); 
} 

我想類似的東西,實際工作。

+0

這個問題還不清楚。也許你應該張貼一些代碼來顯示你想要做的事情。如果你願意,你可以用Java來做這件事。 Java對「靜態」的含義有不同的看法,包括一種根本不是靜態的靜態(與嵌套類相關)。 – 2014-10-17 23:41:14

+0

@彼得好了,完成了。不是Java,因爲我不是Java程序員。 – 2014-10-17 23:54:54

回答

0

我想你會在C#中做的最好的是這樣的:

public class BaseClass 
{ 
    public virtual string InstanceProperty 
    { 
     get { return StaticProperty; } 
    } 

    public static string StaticProperty 
    { 
     get { return "BaseClass"; } 
    } 
} 

public class Derived1Base : BaseClass 
{ 
    public override string InstanceProperty 
    { 
     get { return StaticProperty; } 
    } 

    public new static string StaticProperty 
    { 
     get { return "Derived1Base"; } 
    } 
} 

public class Derived1Derived1Base : Derived1Base 
{ 
} 

public class Derived2Base : BaseClass 
{ 
    public override string InstanceProperty 
    { 
     get { return StaticProperty; } 
    } 

    public new static string StaticProperty 
    { 
     get { return "Derived2Base"; } 
    } 
} 
+0

它也可以使用反射,雖然恕我直言,這將是一個較差的解決方案。就這個特定的解決方案(John的例子)而言,它是恕我直言的正確方法。但是,我會使靜態成員字符串consts而不是屬性(更符合原始示例,但使用「const」而不是「靜態只讀」)。例如。 「public const string Property =」Base「」,然後是「新的公共常量字符串屬性=」孩子1「」等,該代碼將更加簡潔和高效。 – 2014-10-18 00:10:32

+0

@Peter常量很好,除了我需要一個字符串數組,我不認爲它可以是常量。 – 2014-10-18 00:45:07

+1

@GerardoMarset:沒錯。不能用編譯時文字表達的東西不能是const(+)。但是,當他們可以做到的時候,你也可以讓事情成爲常量。 (+)(我不記得語言規範的要求,但這是一個合理的概括)。 – 2014-10-18 01:05:08

1

由於Peter Duniho said,這可以用反射來完成。

例如,這些可以在基類中定義:

public const string Property = "Base"; 

public virtual string InstanceProperty 
{ 
    get 
    { 
     return (string)this.GetType() 
      .GetField("Property", BindingFlags.Public | BindingFlags.Static) 
      .GetValue(null); 
    } 
} 

,然後將每個派生類只是具有使用new關鍵字重新定義Property