有没有办法_somehow_使用枚举值来传递方法调用作为该方法的泛型参数?

时间:2011-05-25 08:02:02

标签: c# generics enums

(这个问题可能没有多大意义。很难写出来。如果你能说得更清楚,请随意更新。)

我有一个枚举:

public enum nodeTypes 
{ 
    Part = 1, 
    SelectListValue, 
    MultiSelectListValue, 
    RepeatingPart,
    ...
}

带切换案例的方法:

switch (type)
{
    case nodeTypes.SelectListValue:
        GenerateSubNode<SelectListValue>(parent, root, depth, true);
        break;
    case nodeTypes.MultiSelectListValue:
        GenerateSubNode<MultiSelectListValue>(parent, root, depth, true);
        break;
    case nodeTypes.Part:
        GenerateSubNode<Part>(parent, root, depth, true);
        break;
    case ....
 }

另一种方法:

private void GenerateSubNode<ComponentType>(Container parent, ZForm root, int depth, bool isContainer) where ComponentType : Component, new()
{
    ...
    var c = new ComponentType();
    ...
}

有没有办法把那个switch case语句写成1个班轮?感觉就像是重复的代码。

3 个答案:

答案 0 :(得分:1)

可能你会尝试像WRONG一样:

    List<ComponentType> types = new List { SelectListValue, MultiSelectValue,...}
    ....
    CompenentType type = types[(int)type];
    GenerateSubNode<type>(parent, root,depth, true);

或者你可以使用工厂模式。

在好评后编辑:

class VehiculeCreation
{ public static List<Type> vehicules = new List<Type> { typeof(Car), typeof(motor) };
enum Vehicule 
{
    Car = 0,
    Motor = 1,
};


static void Main()
{
    vehicule cars = GenerateVehicules((int)Vehicule.Car);
    vehicule motors = GenerateVehicules((int)Vehicule.Motor);
    cars.print();
    motors.print();

    Console.ReadLine();
}

public abstract class vehicule
{
    public abstract void print();
}

public class Car : vehicule
{
    public override void print() {Console.WriteLine("I am a car");}
}

public class motor : vehicule
{
    public override void print() { Console.WriteLine("I am a motor"); }
}

public static vehicule GenerateVehicules(int index)
{
    return (vehicule)System.Activator.CreateInstance(vehicules[index]);
}

}

答案 1 :(得分:1)

你也可以用反射来做到这一点:

typeof( ClassWhereGenerateSubNodeMethodIs ) //alternativly, this.GetType()
   .GetMethod( "GenerateSubNode" )
   .MakeGenericMethod( Type.GetType( "namespace.where.type.classes.are." + type.ToString() ) )
   .Invoke( this, new object[ ] { parent, root, depth, true} );
传递给this

Invoke是调用女巫GenerateSubNode的实例,如果GenerateSubNode是静态的,则在这里传入null。

答案 2 :(得分:0)

这样的东西?

Dictionary<nodeTypes, Action<Container, ZForm, int, bool>> generateActions = new Dictionary<nodeTypes, Action<Container, ZForm, int, bool>>
{ 
  {nodeTypes.SelectListValue, GenerateSubNode<SelectListValue> },
  {nodeTypes.MultiSelectListValue, GenerateSubNode<MultiSelectListValue> },
  // .. so on
}

然后使用它:

generateActions[type](parent, root, depth, true);
// todo: does action exist? validation