2014-10-17 153 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

相关问题