mercoledì 10 agosto 2011

How To: create a Virtual Property

Una delle tante possibilità offerte da "virtual" ( argomento discusso più volte nel blog ) è di poter ovviare all' new se abbiamo ereditato una classe.

In questo esempio propongo due versioni differenti della stessa classe, Property.
La prima cProperty contine una proprietà di tipo string.
La seconda vProperty contiene una proprietà virtuale di tipo string.

Le classi MyCProperty e MyVProperty ereditano rispettivamente cProperty e vProperty.

public class cProperty

{
private string _Property;
public string Property
{
get { return _Property; }
set { _Property = value; }
}
}

public class vProperty
{
private string _Property;
public virtual string Property
{
get { return _Property; }
set { _Property = value; }
}
}


public class MyCProprerty : cProperty
{
private string _Property;
public new string Property
{
get { return _Property; }
set { _Property = value; }
}
}

public class MyVProprerty : vProperty
{
private string _Property;

public override string Property
{
get { return _Property; }
set { _Property = value; }
}
}



Nel primo caso se tolgo il New e compilo il compilatore stesso mi avvisa che devo utilizzare il new.

Nel secondo caso se tolgo l' Ovveride e compilo il compilatore mi avvisa che la base espone già la stessa proprietà.

Rimane pur vero che in entrami i casi posso comunque sfruttare il polimorfismo e ottenere quindi qualcosa di simile.

public class TestCProperty : cProperty

{
private DateTime _NProperty = DateTime.Now;

public DateTime NProperty
{
get { return DateTime.Parse(Property); }
set { Property = value.ToString(); }
}
}


public class TestVProperty : vProperty
{
private DateTime _NProperty = DateTime.Now;

public DateTime NProperty
{
get { return DateTime.Parse(Property); }
set { Property = value.ToString(); }
}
}


Nessun commento: