编译从泛型(C#)创建强类型对象的错误

时间:2015-03-19 17:36:55

标签: c# generics

这是我的课程......我已经删除了除了最低限度的代码之外的所有内容来说明问题区域。下面,我已经标记了没有用代码注释编译的行(它们在Mapping.GetMapTuples()中)

public class MappingSource<T>
{
    protected Dictionary<string, T> dictMap = new Dictionary<string, T>();
    public MappingSource()
    {
    }
    public T GetValue(string key)
    {
        T value;
        if (dictMap.TryGetValue(key, out value))
        {
            return value;
        }
        return default(T);
    }
}
public class Mapping<S, D>
{
    MappingSource<S> _source1;
    MappingSource<D> _source2;
    List<Tuple<string, string>> tuples;
    public Mapping(MappingSource<S> source1, MappingSource<D> source2)
    {
        tuples = new List<Tuple<string, string>>();
        _source1 = source1;
        _source2 = source2;
    }
    public List<MapTuple<S, D>> GetMapTuples<S, D>()
    {
        List<MapTuple<S, D>> list = new List<MapTuple<S, D>>();
        foreach (Tuple<string, string> tuple in tuples)
        {
            // here I need to be able to return a list of MapTuple
            // objects.  I tried three variations; none of them work;

            // this way doesn't work
            // "Cannot implicitly convert 'D' to 'D[C:\test\Form1.cs(166)]'
            S vs = _source1.GetValue(tuple.Item1);
            D vd = _source2.GetValue(tuple.Item2);
            MapTuple<S, D> mapTuple = new MapTuple<S, D>(vs, vd);

            // this way doesn't work; it doesn't like the type var
            // The best overloaded method match for 'Examples16.MapTuple<S,D>.MapTuple(S,D)' has some invalid arguments
            var vsv = _source1.GetValue(tuple.Item1);
            var vdv = _source2.GetValue(tuple.Item2);
            MapTuple<S, D> mapTuple2 = new MapTuple<S, D>(vsv, vdv);

            // this way doesn't work; same error as the first way
            // "Cannot implicitly convert 'D' to 'D[C:\test\Form1.cs(166)]'
            var vsv2 = _source1.GetValue(tuple.Item1);
            var vdv2 = _source2.GetValue(tuple.Item2);
            MapTuple<S, D> mapTuple3 = new MapTuple<S, D>((S)vsv2, (D)vdv2);
        }
        return null;
    }
}
public class MapTuple<S, D>
{
    S _source;
    D _destination;
    public MapTuple(S source, D destination)
    {
        _source = source;
        _destination = destination;
    }
}

1 个答案:

答案 0 :(得分:3)

唯一需要的是:

public List<MapTuple<S, D>> GetMapTuples()

请注意,该函数不再有类型参数。我假设编译器已经警告过你,这些S和D基本上是 shadow 为类定义的外部。以下是我从编译器收到的消息:

Type parameter 'S' has the same name as the type parameter from outer type 'Mapping<S, D>'

因此,此处定义SD

MappingSource<S> _source1;
MappingSource<D> _source2;

不是这里定义的(并在方法中使用):

GetMapTuples<S, D>()

查看fiddle