我的方法:如何重构重载方法
public MyReturnType MyMethod(Class1 arg)
{
//implementation
}
public MyReturnType MyMethod(Class2 arg)
{
//implementation
}
//...
public MyReturnType MyMethod(ClassN arg)
{
//implementation
}
十进制数,字符串,日期时间在[1类,...,ClassN]
和一个常用的方法:
public MyReturnType MyMethod(object obj)
{
if(obj == null)
throw new ArgumentNullException("obj");
if(obj is MyClass1)
return MyMethod((Class1)obj);
if(obj is MyClass2)
return MyMethod((Class2)obj);
//...
if(obj is MyClassN)
return MyMethod((ClassN)obj);
return MyMethod(obj.ToString()); //MyMethod(string) implemented.
}
如何我可以重构这段代码吗?我可以使用属性和组件模型,像这样:
public class MyAttribute : Attribute
{
public Type Type { get; set; }
}
public MyReturnType MyMethod(object obj)
{
if(obj == null)
throw new ArgumentNullException("obj");
var protperty = TypeDescriptor.GetProperties(this, new Attribute[] { new MyAttribute() })
.Cast<PropertyDescriptor>().FirstOrDefault(x =>
x.GetAttribute<MyAttribute>().Type.IsInstanceOfType(obj));
if (protperty != null)
return protperty.GetValue(obj) as MyReturnType;
return MyMethod(obj.ToString());
}
但它看起来很难理解,并且可能会产生一些错误。例如,如果有人宣称像
[MyAttribute(Type = ClassNplus1)]
public NotMyReturnType MyMethod(ClassNplus1 arg);
任何其他的想法如何创建可扩展的系统,在增加新的类只需要添加一个方法的方法? (在一个地方添加代码)
是的,这看起来像我在找什么,但我可以使用3.5框架。有没有可能模拟它? 感谢您的链接。 – Steck
我自己并没有实现这个模式,但是当与同事聊天时,常常会使用双重调度模式。这里描述 - > http://www.garyshort.org/blog/archive/2008/02/11/double-dispatch-pattern.aspx。希望这有助于 – mattythomas2000