Using Constructor to Copy A Class with Different Generic Types in C#
I have a Data<TData, TKey>
class that basically wraps around a dictionary. I want to have a constructor that can take another Data class, copy the values, and take a new key.
C# generics seem to prevent me from doing this however, because the Data class does not have to have the sam开发者_JAVA百科e type of key. All I care about is copying the values and then using a new key for a dictionary.
public class Data<TData, TKey>
{
private Dictionary<TKey, List<TData>> keyedData;
public delegate TKey Key(TData row);
public Data(Data<T,K> data, Key keyDelegate, string keyName)
: this(data.Values, keyDelegate, keyName)
{
}
}
The Data<T,K>
will not work, of course. If the constructor takes Data<TData, TKey>
, though, it forces both the passed in class and the new class to have the same type key. They likely will not have the same type key. There should be a way to pass in Data<TData,?>
as one would in Java.
Perhaps something like...
public interface IData<TData>
{
IEnumerable<TData> Values { get; }
}
public class Data<TData, TKey> : IData<TData>
{
private Dictionary<TKey, List<TData>> keyedData;
public delegate TKey Key(TData row);
public Data(IData<TData> data, Key keyDelegate, string keyName)
: this(data.Values, keyDelegate, keyName)
{
//...
}
}
Alternatively, you could make a true generic method to deal with it.
public class Data<TData, TKey>
{
//...
public void Populate<TOtherKey>(Data<TData, TOtherKey> otherData)
{
// copy otherData.Values into my values
}
}
Then the consumer would do something like:
Data<DataType, Key1> data1 = new Data<DataType, Key2>(/*blah blah*/);
Data<DataType, Key2> data2 = new Data<DataType, Key2>(/*blah blah*/).Populate(data1);
精彩评论