Skip to content

Instantly share code, notes, and snippets.

@AdmiralSnyder
Last active August 4, 2020 14:22
Show Gist options
  • Save AdmiralSnyder/71b2d7cdc3312aba73f832000c2bf8b7 to your computer and use it in GitHub Desktop.
Save AdmiralSnyder/71b2d7cdc3312aba73f832000c2bf8b7 to your computer and use it in GitHub Desktop.
a way to have a dictionary to a subset of types, for mapping classes to tags, for example
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp1
{
class TypeBase<TInterface>
{
public virtual Type TheInnerType { get; }
}
class TypeBase<TInterface, TThis>: TypeBase<TInterface> where TThis : TypeBase<TInterface, TThis>
{ }
class Type<TType, TThis, TInterface> : TypeBase<TInterface, TThis>
where TThis : Type<TType, TThis, TInterface>
where TType : TInterface
{ }
class Type<TType> : Type<TType, Type<TType>, ISomeInterface>
where TType : ISomeInterface
{
public static TypeBase<ISomeInterface> Instance = new Type<TType>();
private static Type InnerType = typeof(TType);
public override Type TheInnerType => InnerType;
}
//these are arbitrary declarations
interface ISomeInterface { } // this interface is the discrimination for the allowed types in the dict
class MyType1 : ISomeInterface { }
class MyType2 : ISomeInterface { }
class MyType3 { }
class Class4
{
public static Dictionary<byte, TypeBase<ISomeInterface>> dict = new Dictionary<byte, TypeBase<ISomeInterface>>
{
[ (byte)0x01 ] = Type<MyType1>.Instance,
[ (byte)0x02 ] = Type<MyType2>.Instance,
// [(byte)0x03] = Type<MyType3>.Instance, // doesn't compile
};
public static Type GetType(byte idx) => dict[idx].TheInnerType;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment