Non_k Non_k - 1 month ago 14
C# Question

use derived class object in base class

I have a base class which contain helper method, and I have some derived classes which contain some virtual methods.

so, I want to know how can I use the derived class object in the base classes virtual methods?

derived class

class myclass :baseClass
{
public string id { get; set; }

public string name { get; set; }

}


base class

public abstract class baseClass
{

public virtual object FromStream()
{
string name, type;

List<PropertyInfo> props = new List<PropertyInfo>(typeof(object).GetProperties()); // here I need to use derived class object

foreach (PropertyInfo prop in props)
{
type = prop.PropertyType.ToString();
name = prop.Name;

Console.WriteLine(name + " as "+ type);
}
return null;
}


main

static void Main(string[] args)
{
var myclass = new myclass();
myclass.FromStream(); // the object that I want to use it

Console.ReadKey();
}

L J L J
Answer

As the method FromStream is checking the properties of an object, I think you could use generics.

Example Code:

public abstract class BaseClass
{
    public virtual object FromStream<T>(string line)
    {
        string name, type;

        List<PropertyInfo> props = new List<PropertyInfo>(typeof(T).GetProperties()); 

        foreach (PropertyInfo prop in props)
        {
            type = prop.PropertyType.ToString();
            name = prop.Name;

            Console.WriteLine(name + " as " + type);
        }
        return null;
    }
}

public class MyClass : BaseClass
{
    public string id { get; set; }

    public string name { get; set; }
}

To consume:

var myclass = new MyClass();
myclass.FromStream<MyClass>("some string"); 

Any type of which the properties needs to be checked can be passed in by doing so:

public virtual object FromStream<T>(string line)

EDIT: Please also note that you can follow the approach mentioned by @Jon Skeet - i.e to use GetType().GetProperties()

In that case you could write the FromStream method as below:

public virtual object FromStream(string line)
{
    string name, type;

    List<PropertyInfo> props = new List<PropertyInfo>(GetType().GetProperties()); 

    foreach (PropertyInfo prop in props)
    {
        type = prop.PropertyType.ToString();
        name = prop.Name;

        Console.WriteLine(name + " as " + type);
    }
    return null;
}
Comments