在我的GUI中,有一个客户下拉列表。每个客户都有一个与之关联的类,其中包含与该客户关联的方法(例如,加载其发票格式等)。每个客户类都实现了“ ICustomer”接口,但是方法的内容不同。
调用类具有ICustomer
属性-我想将其设置为下拉列表中所选值表示的类。像这样的伪代码:
public interface ICustomer
{
int GetInvoice();
}
和
Class Caller()
{
public ICustomer Customer { get; set; }
public void Choose(string customerName)
{
Customer = //??? ["Get class where name == customerName"];
var foo = Customer.GetInvoice();
}
}
从我非常有限的理解和混乱的Internet搜索来看,我认为我需要使用反射来实现这一点,但是到目前为止,我还没有从界面返回特定的,运行时设置的类。我将如何实现这一目标?
答案 0 :(得分:1)
var type = Type.GetType(customerName);
ICustomer customer = (ICustomer)Activator.CreateInstance(type);
var invoice = customer.GetInvoice();
请注意,customerName
必须是名称空间限定的名称。因此,如果要保留所有用户类在X.Y.Z
命名空间中,则必须输入"X.Y.Z." + customerName
。