[英]Define a single C# method which accepts any object that can be used with square brackets
I'm implementing a method that, given some data retrieved via DataRowView or DbDataReader, hydrates a DTO. 我正在实现一种方法,给定一些通过DataRowView或DbDataReader检索的数据,为DTO提供水合作用。
So, both of the data sources implement the possibility to retrieve a particular field value through 因此,两个数据源都实现了通过检索特定字段值的可能性
public object this[string name] { get; }
But this behavior is not constrainted by a common interface between the two classes so I cannot use it, and have to write the hydration code twice without changing a single bit. 但是这种行为不受两个类之间的公共接口的约束,因此我不能使用它,并且必须在不改变单个位的情况下两次写入水合代码。 Which is bad. 这很糟糕。
public MyDTO Hydrate(DataRowView data)
{
MyDTO f_return = new MyDTO();
f_return.Foo = (string)data["foo"];
f_return.Bar = (uint)data["bar"];
f_return.Baz = (DateTime)data["baz"];
return f_return;
}
public MyDTO Hydrate(DbDataReader data)
{
MyDTO f_return = new MyDTO();
f_return.Foo = (string)data["foo"];
f_return.Bar = (uint)data["bar"];
f_return.Baz = (DateTime)data["baz"];
return f_return;
}
Am I missing some C# syntax that would allow me to define a single method which constraints the input to any object that can be accessed via square brackets? 我是否缺少一些C#语法,它允许我定义一个方法来限制任何可以通过方括号访问的对象的输入?
Something like this 像这样的东西
public MyDTO Hydrate(object[string] data)
Thanks in advance! 提前致谢!
Am I missing some C# syntax that would allow me to define a single method which constraints the input to any object that can be accessed via square brackets? 我是否缺少一些C#语法,它允许我定义一个方法来限制任何可以通过方括号访问的对象的输入?
No; 没有; there's no C# syntax for expressing "something that is indexable", other than creating an interface
with that indexer, ie 没有C#语法来表达“可索引的东西”,除了用该索引器创建一个interface
,即
interface ISomeInterface {
object this[string name] {get;}
}
and limiting yourself to instances of ISomeInterface
, or some generic <T>
with the where T : ISomeInterface
constraint. 并限制自己使用ISomeInterface
实例,或者使用where T : ISomeInterface
约束的一些通用<T>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.