Hao*_*Hao 5 c# attributes design-patterns enforcement
让我说我有
public delegate DataSet AutoCompleteDelegate(
string filter, long rowOffset);
Run Code Online (Sandbox Code Playgroud)
我可以使用以下类来强制执行该方法签名吗?(只是一个想法):
public class MiddleTier
{
[Follow(AutoCompleteDelegate)]
public DataSet Customer_AutoComplete(string filter, long rowOffset)
{
var c = Connect();
// some code here
}
[Follow(AutoCompleteDelegate)]
public DataSet Item_AutoComplete(string filter, long rowOffset)
{
var c = Connect();
// some code here
}
// this should give compilation error, doesn't follow method signature
[Follow(AutoCompleteDelegate)]
public DataSet BranchOffice_AutoComplete(string filter, string rowOffset)
{
var c = Connect();
// some code here
}
}
Run Code Online (Sandbox Code Playgroud)
[编辑]
目的:我已经将属性放在我的middletier的方法中.我有这样的方法:
public abstract class MiddleTier : MarshalByRefObject
{
// Operation.Save is just an enum
[Task("Invoice", Operation.Save)]
public Invoice_Save(object pk, DataSet delta);
[Task("Receipt", Operation.Save)]
public Receipt_Save(object pk, DataSet delta);
// compiler cannot flag if someone deviates from team's standard
[Task("Receipt", Operation.Save)]
public Receipt_Save(object pk, object[] delta);
}
Run Code Online (Sandbox Code Playgroud)
然后在运行时,我将迭代所有middletier的方法并将它们放到集合中(属性在这里有很多帮助),然后将它们映射到winform的委托函数(由界面,基于插件的系统促进)作为加载
我在想是否可以使属性更具自描述性,因此编译器可以捕获不一致性.
namespace Craft
{
// public delegate DataSet SaveDelegate(object pk, DataSet delta); // defined in TaskAttribute
public abstract class MiddleTier : MarshalByRefObject
{
[Task("Invoice", SaveDelegate)]
public abstract Invoice_Save(object pk, DataSet delta);
[Task("Receipt", SaveDelegate)]
// it's nice if the compiler can flag an error
public abstract Receipt_Save(object pk, object[] delta);
}
}
Run Code Online (Sandbox Code Playgroud)
我在想如果把方法放在每个类上,总是实例化一个Remoting对象会有点过分.将它们放在单独的类中,可能更难以促进代码重用,假设Invoice_Save需要一些关于Receipt_Open的信息.事实上,我甚至在这里有一个报告(水晶),它从Remoting middletier DataSet中获取数据,在调用的方法中,它获取其他方法的一些信息并合并到它自己的DataSet中,它们都发生在middletier上,没有几次往返,一切都在服务器端完成(中间层)
Rob*_*ski 11
其他答案显然是有效的,但没有什么可以防止您忘记[Follow(AutoCompleteDelegate)]
在您的方法上应用属性.
我认为你最好将转换方法转换为实现接口的类:
public interface IAutoComplete
{
DataSet Complete(string filter, long rowOffset);
}
public class CustomerAutoComplele : IAutoComplete
{
public DataSet Complete(string filter, long rowOffset)
{
var c = Connect();
// some code here
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用工厂方法模式获取"自动完成程序":
public static class AutoCompleteFactory
{
public static IAutoComplete CreateFor(string purpose)
{
// build up and return an IAutoComplete implementation based on purpose.
}
}
Run Code Online (Sandbox Code Playgroud)
要么
public static class AutoCompleteFactory
{
public static IAutoComplete CreateFor<T>()
{
// build up and return an IAutoComplete implementation based on T which
// could be Customer, Item, BranchOffice class.
}
}
Run Code Online (Sandbox Code Playgroud)
完成后,您可以查看控制和依赖注入的反转,以避免在工厂方法中对自动完成实现的列表进行硬编码.