0

我有一个包含辅助方法的基类,并且我有一些包含一些虚拟方法的派生类。

所以,我想知道如何在基类虚拟方法中使用派生类对象?

派生类

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

    public string name { get; set; }

}

基类

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;
    }

主要的

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

        Console.ReadKey();
    }
4

1 回答 1

1

由于该方法FromStream正在检查properties对象的 ,我认为您可以使用generics.

示例代码:

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; }
}

消费:

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

任何type需要检查的属性都可以通过这样做传入:

public virtual object FromStream<T>(string line)

编辑:另请注意,您可以遵循@Jon Skeet 提到的方法 - 即使用GetType().GetProperties()

在这种情况下,您可以编写如下FromStream方法:

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;
}
于 2016-10-12T12:31:02.543 回答