Why is use of specifc enum invalid in generic method with enum as the type - unity3d

Why does this line of code (context below)
if (spellEnum == Spell.Fireball) return "Fire ball";
produce the error:
'Spell' is a type parameter, which is not valid in the given context
public abstract class DataSet : ScriptableObject
{
public abstract string DisplayName<T>(T arg) where T : Enum;
}
public enum Spell { Fireball, Icestorm, MagicMissile };
public class SpellDataSet : DataSet
{
public override string DisplayName<Spell>(Spell spellEnum)
{
if (spellEnum == Spell.Fireball) return "Fire ball";
return "Other spell";
}
}
public class DataLibrary
{
void main()
{
SpellDataSet spellDataSet = new SpellDataSet();
strint test = spellDataSet.DisplayName(Spell.Fireball);
}
}
I want a generic way to access data about various types (spells, items, characters), with data about specific kinds of that type (Spell1, Spell2, etc) accessed via that type's respective enum (Spell), and a universal method (defined in abstract class) across all types will produce the user-friendly name (DisplayName).

I still don't understand why the original code produces an error, but I have achieved what I wanted via making the abstract class generic, rather than only the DisplayName method. Code that works:
public abstract class DataSet<T> : ScriptableObject where T: Enum
{
public abstract string DisplayName(T arg);
}
public enum Spell { Fireball, Icestorm, MagicMissile };
public class SpellDataSet : DataSet<Spell>
{
public override string DisplayName(Spell spellEnum)
{
if (spellEnum == Spell.Fireball) return "Fire ball";
return "Other spell";
}
}
public class DataLibrary
{
void main()
{
SpellDataSet spellDataSet = new SpellDataSet();
string test = spellDataSet.DisplayName(Spell.Fireball);
}
}

Related

Autofac: registering hierarchy of classes

I am struggling to register with Autofac a hierarchy of classes and interfaces.
I have an interface IMyService defined as below:
public interface IMyService
{
void DoMyService();
}
And I have two abstract classes with implement this interface and called MyServiceA, and MyServiceB:
public abstract class MyServiceA : IMyService
{
public abstract DoMyService();
}
public abstract class MyServiceB : IMyService
{
public abstract DoMyService();
}
Moreover I have a second-level hierarchy for each of the two aforementioned services: MyServiceA1, MyServiceA2, MyServiceB1 and MyServiceB2:
public class MyServiceA1 : MyServiceA
{
public MyServiceA1() : base() {}
public void DoMyService()
{
// Implementation goes here
}
}
public class MyServiceA2 : MyServiceA
{
public MyServiceA2() : base() {}
public void DoMyService()
{
// Implementation goes here
}
}
public class MyServiceB1 : MyServiceB
{
public MyServiceB1() : base() {}
public void DoMyService()
{
// Implementation goes here
}
}
public class MyServiceB2 : MyServiceB
{
public MyServiceB2() : base() {}
public void DoMyService()
{
// Implementation goes here
}
}
I have in input two enums FirstEnum and SecondEnum used to select which of the four concrete types to instantiate:
public enum FirstEnum
{
SvcA,
SvcB
}
public enum SecondEnum
{
Svc1,
Svc2
}
I want to register IMyService and by providing two enums, It will automatically instantiate the good concrete type.
For instance, if I want to resolve an IMyService and I provide FirstEnum.SvcB and SecondEnum.Svc2, it should instantiate the concrete type MyServiceB2 class. Moreover this hierarchy might be updated by adding some other concrete types etc, so I need a generic way of doing it
Does anyone have a clue to help me?
Thanks
If you want to create a specific service dynamically depending on a set of parameters, this is a good use case for an abstract factory:
public interface IMyServiceFactory
{
IMyService Create(FirstEnum e1, SecondEnum e2);
}
public class MyServiceFactory : IMyServiceFactory
{
private readonly ILifetimeScope scope;
public MyServiceFactory(ILifetimeScope scope)
{
if (scope == null)
throw new ArgumentNullException("scope");
this.scope = scope;
}
public IMyService Create(FirstEnum e1, SecondEnum e2)
{
if (e1 == FirstEnum.SvcA)
{
if (e2 == SecondEnum.Svc1)
{
return scope.Resolve<MyServiceA1>();
}
else //svc2
{
return scope.Resolve<MyServiceA2>();
}
}
else //B
{
if (e2 == SecondEnum.Svc1)
{
return scope.Resolve<MyServiceB1>();
}
else //svc2
{
return scope.Resolve<MyServiceB2>();
}
}
}
}
And now your consumer need to get the factory injected instead of the service:
public class MyServiceConsumer
{
private readonly IMyServiceFactory factory;
public MyServiceConsumer(IMyServiceFactory factory)
{
this.factory = factory;
}
public void Do()
{
//var service = this.factory.Create
}
}
Registration :
Autofac.ContainerBuilder builder = new Autofac.ContainerBuilder();
builder.RegisterType<MyServiceA1>().AsSelf().AsImplementedInterfaces();
builder.RegisterType<MyServiceA2>().AsSelf().AsImplementedInterfaces();
builder.RegisterType<MyServiceB1>().AsSelf().AsImplementedInterfaces();
builder.RegisterType<MyServiceB2>().AsSelf().AsImplementedInterfaces();
builder.RegisterType<MyServiceFactory>().As<IMyServiceFactory>();
builder.RegisterType<MyServiceConsumer>();
//and quick test resolve
var container = builder.Build();
var test = container.Resolve<MyServiceConsumer>();

Haxe access Class<T> static fields

I have three classes and I would like to be able to call static functions from the returned Class<Access>. I would like to select class type based on conditions.
class Access {
public static function get(item: Int): Int { return -1; }
public static function getAccessType(): Class<Access> {
if(Client.hasConnection())
return Remote;
else return Local;
}
}
class Remote extends Access {
override public static function get(item: Int): Int { return Server.getItem(item); }
}
class Local extends Access {
override public static function get(item: Int): Int { return Client.getItem(item); }
}
You can't override a static function in Haxe.
But you can probably achieve what you're trying to do by simply removing the override in Remote and Local
Can be done with singletons.
However, still the question might relevant whether such feature in Haxe even exists.
Depending on target, you may be able to cast a class to an interface/typedef to pull out values in a type-safe-ish way. "override" does not work for static methods
class Test {
static function pick(z:Bool):HasGetItem {
return z ? cast A : cast B;
}
static function main() {
trace("Haxe is great!");
trace(pick(false).getItem(1));
trace(pick(true).getItem(2));
}
}
#:keep class A {
public static function getItem(i:Int):Int return 10;
}
#:keep class B {
public static function getItem(i:Int):Int return 5;
}
typedef HasGetItem = {
getItem:Int->Int
}
https://try.haxe.org/#b2b87

resolve all given the Type

From the Autofac documentation I can see how to get all registrations for a class T:
public T[] ResolveAll<T>()
{
return _container.Resolve<IEnumerable<T>>().ToArray();
}
But when I only have the Type available, how can I get the equivalent results?
public Array ResolveAll(Type service)
{
return _container.Resolve( ???
}
I am trying to implement a wrapper class which has a pre-defined interface.
EDIT
For quick reference, the answer from Matthew Watson (with relevant ideas from David L) is:
public Array ResolveAll(Type service)
{
var typeToResolve = typeof(IEnumerable<>).MakeGenericType(service);
return _container.Resolve(typeToResolve) as Array;
}
Here is an example. I've added asserts to prove that the types returned from ResolveAll<T>(this IContainer self) are the same (and in the same order) as those returned from ResolveAll(this IContainer self, Type type):
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Autofac;
using Autofac.Core;
namespace AutofacTrial
{
public abstract class Base
{
public abstract string Name { get; }
public override string ToString()
{
return Name;
}
}
public sealed class Derived1: Base
{
public override string Name
{
get
{
return "Derived1";
}
}
}
public sealed class Derived2: Base
{
public override string Name
{
get
{
return "Derived2";
}
}
}
public sealed class Derived3: Base
{
public override string Name
{
get
{
return "Derived3";
}
}
}
static class Program
{
static void Main()
{
var builder = new ContainerBuilder();
builder.RegisterType<Derived1>().As<Base>();
builder.RegisterType<Derived2>().As<Base>();
builder.RegisterType<Derived3>().As<Base>();
var container = builder.Build();
var array1 = container.ResolveAll(typeof(Base));
var array2 = container.ResolveAll<Base>();
Trace.Assert(array1.Length == 3);
Trace.Assert(array2.Length == 3);
for (int i = 0; i < array1.Length; ++i)
{
Trace.Assert(array1[i].GetType() == array2[i].GetType());
Console.WriteLine(array1[i]);
}
}
public static T[] ResolveAll<T>(this IContainer self)
{
return self.Resolve<IEnumerable<T>>().ToArray();
}
public static object[] ResolveAll(this IContainer self, Type type)
{
Type enumerableOfType = typeof(IEnumerable<>).MakeGenericType(type);
return (object[]) self.ResolveService(new TypedService(enumerableOfType));
}
}
}
The underling implementation is the same
I also used Reflector to look at the implementation of Resolve<IEnumerable<T>>(), and it winds up doing this:
public static TService Resolve<TService>(this IComponentContext context, IEnumerable<Parameter> parameters)
{
return (TService) context.Resolve(typeof(TService), parameters);
}
which calls:
public static object Resolve(this IComponentContext context, Type serviceType, IEnumerable<Parameter> parameters)
{
return context.ResolveService(new TypedService(serviceType), parameters);
}
So the two must be equivalent, since they are implemented that way.
You can invoke _container.Resolve by calling your wrapped method via reflection (MSDN), but in doing so you will lose your compile-time type safety.
public class Container
{
public T[] ResolveAll<T>()
{
return _container.Resolve<IEnumerable<T>>().ToArray();
}
public object ResolveAllGeneric(Type t)
{
MethodInfo method = GetType().GetMethod("ResolveAll")
.MakeGenericMethod(new Type[] { t });
return method.Invoke(this, new object[] { });
}
}

Autofac: Open generics and base interfaces

Given the following interfaces and classes, is there a way in Autofac to
Register a Provider<T> for all classes that have a ProviderAttribute, with T being the type of such a class (Think registering open generics and resolving them with Autofac's MakeGenericType())
Inject these registered providers as, drum roll, IEnumerable<IProviderBase> into the constructor of other classes
Overview:
public class ProviderAttribute : Attribute { }
public interface IProviderBase
{
Type Type { get; }
}
public interface IProvider<T> : IProviderBase
{
DoSomething(T t);
}
public class Provider<T> : IProvider<T>
{
public Type Type
{
get { return typeof (T); }
}
public DoSomething(T t)
{
//...
}
}
I have come up with a crude solution:
var types = GetProviderTypes();
foreach (var type in types)
{
var t = typeof (Provider<>).MakeGenericType(type);
builder.RegisterType(t).As<IProviderBase>();
}

Cast a CustomList<CustomClass> to IList<Interface>

(This is .Net 3.5) I have a class FooList which implements IList and a class FooClass which implements IFoo. A user requires IList<IFoo>. In my implementation, I create a FooList<FooClass>, called X. How do I code my return so that my FooList<FooClass> X becomes his IList<IFoo>?
If I try
return X.Cast( ).ToList( );
he gets an IList<IFoo>, but it is not my FooList; it is a List, and a new one at that.
This isn't going to work out, because a FooList<FooClass> is not an IList<IFoo>. This is why:
var myList = new FooList<FooClass>();
IFoo obj = new SomeOtherFooClass();
IList<IFoo> result = (IList<IFoo>)myList; // hypothetical, wouldn't actually work
result.Add(obj); // uh-oh, now myList has SomeOtherFooClass
You need to either make a copy or use an interface that is actually covariant on the contained type, like IEnumerable<T> instead of IList<T>. Or, if appropriate, you should declare your FooList<FooClass> as an FooList<IFoo> from the get-go instead.
Here is a small implementation that demonstrates my second suggestion:
public interface IFoo { }
public class FooClass : IFoo { }
public class FooList<T> : IList<T>
{
public void RemoveAt(int index) { /* ... */ }
/* further boring implementation of IList<T> goes here */
}
public static void ListConsumer(IList<IFoo> foos)
{
foos.RemoveAt(0); // or whatever
}
public static IList<IFoo> ListProducer()
{
// FooList<FooClass> foos = new FooList<FooClass>(); // would not work
FooList<IFoo> foos = new FooList<IFoo>();
foos.Add(new FooClass());
return foos; // a FooList<IFoo> is an IList<IFoo> so this is cool
}
public static void Demo()
{
ListConsumer(ListProducer()); // no problemo
}