0

im trying to move code from java to c# and i got problem with code syntax.

because in c# dont exist Class<?> and i need to call newInstance() inside Class<?>

in java i have:

private final Map< String, Class< ? extends AbstractAI>> aiMap = new HashMap< String, Class< ? extends AbstractAI>>(); //line code i need to move

public final AI2 setupAI(String name, Creature owner) {
        AbstractAI aiInstance = null;
        try {
            aiInstance = aiMap.get(name).newInstance();//line code i need to move
        }
        catch (Exception e) {
            log.error("[AI2] AI factory error: " + name, e);
        }
        return aiInstance;
    }

if you know solution please help me move this java code into c#. Thanks

  • 6
    Generics are pretty different in general in C# - the closest here would be `Dictionary` but that wouldn't restrict those types to use `AbstractAI`. You'll need to cast the result of `Activator.CreateInstance(type)` to `AbstractAI`. There are potentially other ways round this though, e.g. a `Dictionary>`. I would try to avoid porting Java *directly* - port *idiomatically* instead. – Jon Skeet Dec 08 '16 at 09:27
  • C# doesn't have concept of upper-bound wildcard generics as now (still wishing to write Dictionary` directly in the future), thus `HashMap` equivalent would be `Dictionary` using generic constraint in Type. `final` like keywords on methods doesn't necessary since by default C# methods are not virtual. – Tetsuya Yamamoto Dec 08 '16 at 10:02

1 Answers1

0

C# Generics work totaly different then Java Generics. Take a look at C# vs Java generics.

A possible solution:

    private static readonly Dictionary<String, Factory> aiMap = new Dictionary<string, Factory>();

    public static void Add<T>(string name) where T : AbstractAI, new()
    {
        aiMap.Add(name, new Factory.Implementation<T>());
    }

    public static AI2 SetupAI(String name, Creature owner)
    {
        AbstractAI aiInstance = null;
        try
        {
            aiInstance = aiMap[name].CreateInstance();
        }
        catch (Exception e)
        {
            Console.Error.WriteLine("[AI2] AI factory error: " + name, e);
        }
        return aiInstance;
    }

With following classes:

    public abstract class Factory
    {
        private Factory()
        {

        }
        public abstract AbstractAI CreateInstance();
        public class Implementation<T> : Factory where T : AbstractAI, new()
        {

            public override AbstractAI CreateInstance()
            {
                return new T();
            }
        }
    }

Assuming AbstractAI extends/implements the class/interface AI2

Community
  • 1
  • 1
lokimidgard
  • 1,039
  • 10
  • 26