我有一个包含helper方法的基类,我有一些包含虚方法的派生类。
所以,我想知道如何在基类的虚方法中使用派生类对象?
派生类
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();
}
由于方法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)
EDIT:还请注意,您可以遵循@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;
}