通用方法签名
我有一个加载参考数据的数据访问类。每种类型的实体将执行其自己的存储过程并返回特定于该实体类型的结果集。然后我有一个方法将数据表的返回值映射到实体。所有实体类型都具有相同的公共属性“代码”和“名称”,如何使此方法通用以处理实体类型?类似这样的事情是可以假设的,但属性会导致错误。
private static T MapDataReaderToEntity<T>(IDataReader reader)
{
var entity = typeof (T);
entity.Code = SqlPersistence.GetString(reader, "Code");
entity.Name = SqlPersistence.GetString(reader, "Name");
return entity;
}
我会这样称呼它。
_sourceSystem = MapDataReaderToEntity<SourceSystem>(_reader);
I have a data access class that loads reference data. Each type of entity will execute it's own stored procedure and return a result set specific for that entity type. Then I have a method that maps the returned values from the datatable to the entity. All Entity Types have the same public properties of Code and Name how can I make this method generic to handle a type of entity? Something like this is what would presume but the properties are causing an error.
private static T MapDataReaderToEntity<T>(IDataReader reader)
{
var entity = typeof (T);
entity.Code = SqlPersistence.GetString(reader, "Code");
entity.Name = SqlPersistence.GetString(reader, "Name");
return entity;
}
and I would call it with something like this.
_sourceSystem = MapDataReaderToEntity<SourceSystem>(_reader);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以有一个定义这些属性的接口,然后让您的实体类实现该接口:
现在,您可以向您的方法添加通用约束:
请注意,您还需要
new()
约束来实际构建新实体;它指示任何泛型类型参数都将具有无参数构造函数。You could have an interface that defines those properties, and then have your entity classes implement that interface:
Now, you can add a generic constraint to your method:
Note that you also need the
new()
constraint to actually construct the new entity; it indicates the any generic type argument will have a parameterless constructor.如果您的实体实现了定义了 Code 和 Name 属性的接口,您可能会使用类似以下内容:
如果没有该接口,编译器就无法了解
Code
或Name< /代码> 属性。您需要恢复使用反射或动态代码,或其他一些不太理想的机制来在运行时而不是编译时确定这些属性。
If your entities implement an interface with the Code and Name properties defined, you could potentially use something like:
Without the interface, there is no way for the compiler to know about the
Code
orName
properties. You would need to revert to using Reflection or dynamic code, or some other less-than-ideal mechanism for determining these properties at runtime instead of at compile time.您需要向
MapDataReaderToEntity添加 类型约束
确保任何 T 实现 Code 和 Name 属性设置器,以及无参数构造函数。You need to add a type constraint to
MapDataReaderToEntity<T>
which ensures that any T implements Code and Name property setters, as well as a parameter-less constructor.如果您的所有实体都具有属性
Code
和Name
,我建议让它们实现具有属性Code
的接口ICodedEntity
code> 和Name
,然后定义您的方法,然后您的代码将被编译。
If all of your entities have properties
Code
andName
, I'd suggest having them implement an interfaceICodedEntity
with propertiesCode
andName
, then define your methodthen the code you have will compile.