I'm implementing a method that, given some data retrieved via DataRowView or DbDataReader, hydrates a 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?
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?
No; there's no C# syntax for expressing "something that is indexable", other than creating an interface
with that indexer, ie
interface ISomeInterface {
object this[string name] {get;}
}
and limiting yourself to instances of ISomeInterface
, or some generic <T>
with the where T : ISomeInterface
constraint.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.