Class 基于变量类型的方法

Class 基于变量类型的方法,class,c#-4.0,design-patterns,methods,Class,C# 4.0,Design Patterns,Methods,我有下面的场景 我想从方法返回字符串,但该方法应基于变量类型(type CType) 我需要像这样创建渲染类 public string render(TextBox ctype){ return "its text box"; } public string render(DropDown ctype){ return "its drop down"; } var CType = typeof(TextBox) render(Ctype); 你知道TextBox是一种类型,这就是为什么我

我有下面的场景 我想从方法返回字符串,但该方法应基于变量类型(
type CType

我需要像这样创建渲染类

public string render(TextBox ctype){
return "its text box";
}
public string render(DropDown ctype){
return "its drop down";
}
var CType = typeof(TextBox)
render(Ctype);
你知道TextBox是一种类型,这就是为什么我可以像这样声明类型变量

public string render(TextBox ctype){
return "its text box";
}
public string render(DropDown ctype){
return "its drop down";
}
var CType = typeof(TextBox)
render(Ctype);
我需要像这样调用render方法

public string render(TextBox ctype){
return "its text box";
}
public string render(DropDown ctype){
return "its drop down";
}
var CType = typeof(TextBox)
render(Ctype);
因此,如果Ctype是TextBox类型,它应该调用render(textboxctype) 等等
我怎么做呢?

你应该使用模板功能

public customRender<T>(T ctype)
{
    if(ctype is TextBox){
        //render textbox
    }
    else if(ctype is DropDown){
        //render dropdown
    }
}
publiccustomrender(T ctype)
{
如果(ctype为文本框){
//渲染文本框
}
else if(ctype为下拉列表){
//渲染下拉列表
}
}

希望它会有帮助首先,即使你没有看到
一个
如果
开关
,在某些函数中还是会隐藏一个。如果没有控制流的任何此类分支,在运行时区分编译时未知的类型是不可能的

您可以使用其中一个集合类在运行时构建将实例映射到的映射。例如,可以使用类型创建这样的映射:

var rendererFuncs = new Dictionary<Type, Func<object, string>>();
稍后,您可以像这样调用适当的函数:

rendererFuncs[typeof(TextBox)] = ctype => "its text box";
rendererFuncs[typeof(DropDown)] = ctype => "its drop down";
string renderedValue = rendererFuncs[Ctype.GetType()](Ctype);
或者,如果希望安全起见(如果存在没有适当渲染器的
Ctype
值):

字符串呈现值;
Func渲染器;
if(renderfuncs.TryGetValue(Ctype.GetType(),out渲染器)){
renderedValue=渲染器(Ctype);
}否则{
RenderdValue=“(未找到渲染器)”;
}

请注意,只要
Ctype
的类型与字典中用作键的类型完全相同,此选项就有效;如果您还希望正确识别任何子类型,请删除字典并构建自己的映射,该映射将遍历所搜索类型的继承层次结构(通过使用)。

在这种情况下,泛型参数有什么好处?为什么不直接键入
ctype
Control
并删除泛型参数?问题是我不想使用If或switch case@O.R.Mapper是什么意思?@M.NourBerro:这个答案中建议的方法也可以声明为,例如:
public void customRender(object ctype)
。对于这里描述的实现,不需要泛型参数
@O.R.Mapper,我知道,但我不想使用任何if或switch。编译时是否知道传递给
render
方法的类型,或者仅在运行时?在运行时,我会调用render,但我不知道ctype type@O.R.Mapperi会对其进行测试,并告诉您结果谢谢您的回答:)