我有以下方法:
我该如何重构这段代码?我可以使用属性和组件模型,类似于以下内容:
有没有其他的想法,如何创建一个可扩展的系统,只需要添加一个方法就可以了呢?(在一个地方添加代码)
public MyReturnType MyMethod(Class1 arg)
{
//implementation
}
public MyReturnType MyMethod(Class2 arg)
{
//implementation
}
//...
public MyReturnType MyMethod(ClassN arg)
{
//implementation
}
[Class1, ... , ClassN]中的decimal、string和DateTime
还有一个常用方法:
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);
有没有其他的想法,如何创建一个可扩展的系统,只需要添加一个方法就可以了呢?(在一个地方添加代码)