我有一个名为Rack的抽象基类,我有不同类型的机架,它们是Rack的子机。我希望能够将通用C#对象动态地转换为Rack类的不同子类,以便调用所有子进程作为方法的正确getData方法。这是我到目前为止所做的 下面的代码调用Rack基类中的虚方法。我需要它来调用Rack的子类中的方法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace IO_Interface
{
class Channel
{
private object rack1;
private object rack2;
public Channel()
{
}
public Channel(object h1, object h2)
{
rack1 = h1;
rack2 = h2;
}
public void send()
{
Type rack1Info = rack1.GetType();
Type rack2Info = rack2.GetType();
string name = rack1.ToString();
MethodInfo castMethod = rack1.GetType().GetMethod("getData").;
castMethod.Invoke(rack1.GetType(), null);
}
}
}`
答案 0 :(得分:5)
您要做的是将rack1和rack2声明为Racks,它将是一个抽象类,带有抽象方法GetData。您将它们实例化为Rack的子类。然后,当你在Rack上调用GetData时,它会找到被覆盖的方法并调用它。这是一个例子。
abstract class Rack
{
public abstract void GetData();
}
class ChildRack1 : Rack
{
public override void GetData(){}
}
class ChildRack2 : Rack
{
public override void GetData(){}
}
class Channel
{
private Rack rack1;
private Rack rack2;
public Channel()
{
}
public Channel(Rack h1, Rack h2)
{
rack1 = h1;
rack2 = h2;
}
public void send()
{
rack1.GetData();
}
}
答案 1 :(得分:0)
我认为这将为您提供所需的实施方案:
class Channel
{
private List<Rack> racks;
public Channel()
{
racks = new List<Rack>();
}
public Channel(params Rack[] racks)
{
this.racks = racks.ToList();
}
public void send()
{
foreach (Rack item in racks)
{
item.getData();
}
}
public void SendSpecificRack(Rack rack)
{
//calls the getdata of the rack object passed
rack.getData();
}
}
public class Rack
{
public virtual void getData()
{
Console.WriteLine("Base Rack");
}
}
public class RackChild1 : Rack
{
public override void getData()
{
Console.WriteLine("RackChild1");
}
}
public class RackChild2 : Rack
{
public override void getData()
{
Console.WriteLine("RackChild2");
}
}
用法:
Channel chn = new Channel(new Rack[]{new RackChild1(),new RackChild2()});
chn.send();
RackChild2 rck = new RackChild2();
chn.SendSpecificRack(rck);
输出:
RackChild1
RackChild2
RackChild2