How to allow a method to accept two data types as an argument?

This is the same question I asked a while ago: How to allow a method to accept two data types as an argument?

But the current situation is different .. a lot.

Take this:

public FormResourceSelector(Dictionary<string, Effect> resourceList, string type)

Well, that's okay. Now I am trying to run this:

FormResourceSelector frs = new FormResourceSelector(AreaEffect.EFFECTS, "Area effect");
FormResourceSelector frs2 = new FormResourceSelector(DistanceEffect.EFFECTS, "Distance effect");

Both AreaEffect and DistanceEffect (custom classes) get the effect.

public class AreaEffect : Effect
{
    public static Dictionary<string, AreaEffect> EFFECTS = new Dictionary<string, AreaEffect>();
    ...
}

For some reason, I get the following error when creating a new instance of FormResourceSelector:

Argument 1: cannot convert from 'System.Collections.Generic.Dictionary<string,SCreator.AreaEffect>' to 'System.Collections.Generic.Dictionary<string,SCreator.Effect>'  

by the address:

new FormResourceSelector(AreaEffect.EFFECTS, "Area effect");

I suspect the dictator is a persecution, but I really don't know how to fix it.

EDIT: The easiest way is to allow the entry of the dictionary and the dictionary as a resource in the first piece of code that I gave.

+3
source share
4 answers

?

public class FormResourceSelector<T>
    where T : Effect
{
    public FormResourceSelector(Dictionary<string, T> resourceList, string type)
    {
    }
}
+8

, llia :

public class FormResourceSelector<T> where T : Effect
{
    // Constructor
    public FormResourceSelector(
       Dictionary<string, T> resourceList, string type) 
    {

    }
}
+2

:

public FormResourceSelector(Dictionary<string, Effect> resourceList, string type)
{
    resourceList.Add(new Effect());
}

:

var effects = new Dictionary<string, AreaEffect>();
new FormResourceSelector(effects, "");

Effect , AreaEffect, .

generics, , .

0

- , , - , :

IDictionary<string, object> myDict = new Dictionary<string, string>();
myDict["hello"] = 5; // not an string

: IDictionary < TKey, TValue > .NET 4

0

All Articles