Matrimony Ответов: 1

Переопределение базового свойства


public class A
{
   public string prop 
   {
         get{  ...some logic...; }
   }

   public string method()
   {
       string p =  do something calculation using prop.
       return p;
   }
}  

public class B
{
   // i would like to override property prop,
   // so when i call B.method from client, the return value will be calculated 
   //based on overrided property
}


Что я уже пробовал:

if the property can be override, or only the method can be.
Is there any idea to implement this if keep the property.

1 Ответов

Рейтинг:
9

OriginalGriff

Свойства могут быть переопределены:

public class A
    {
    public virtual string prop
        {
        get { return "A:prop"; }
        }

    public string method()
        {
        string p = prop + " Added";
        return p;
        }
    }

public class B : A
    {
    // i would like to override property prop,
    // so when i call B.method from client, the return value will be calculated 
    //based on overrided property
    public override string prop
        {
        get { return "B:prop"; }
        }
    }

private void MyButton_Click(object sender, EventArgs e)
    {
    A a = new A();
    A b = new B();
    Console.WriteLine("{0},{1}", a.prop, a.method());
    Console.WriteLine("{0},{1}", b.prop, b.method());
Будет генерировать:
A:prop,A:prop Added
B:prop,B:prop Added