I'm modelling a list of strongly typed开发者_JAVA技巧 database keys. Some will be ints, some strings, some guids etc.
EDIT They are strongly typed in the sense that some of the keys will contain integer values, some strings, some uids etc.
So if my class for the Key was "Key" and my list was List<Key>
I'm looking for how to implement the strongly typed aspect. I don't want to use generics as I don't think its appropriate here (prove me wrong though).
I'm thinking of making "Key" and abstract class and making each subclass implement the strongly typed aspect. But this will be messy as well. (see below)
Does anyone have any better ideas?
public abstract class RowKey
{
public string DbName { get; set; }
public abstract object GetTypedValue();
}
public class IntegerRowKey: RowKey
{
public override object GetTypedValue()
{
return 1;
}
}
Why do you think generics are inappropriate here? They were pretty much invented for this scenario:
public class RowKey<T>
{
public string DbName { get; set; }
public T GetValue():
}
// Now use RowKey<int>, RowKey<string>, RowKey<Guid>, etc.
Having an abstract base class that returns object
kind of destroys the whole idea of being strongly-typed, no?
edit: ah, I see what you're getting at. Have a look at this question.
精彩评论