根据指定的枚举值创建动态方法重载

时间:2019-05-04 17:50:57

标签: c# methods enums overloading

我想基于指定的枚举值创建方法重载。

我具有以下方法构造:

public void InsertValue(DataType dataType, ... special values ...) {
   // Do something... 
}

DataType是具有一些值的枚举:

  • 时间
  • 日期
  • 日期时间
  • base64
  • uri

例如: 如果使用枚举值datetime调用该方法,则这种类型的重载应该像这样。

InsertValue(DataType.datetime, DateTime date, int parent_id, bool absolute_value);

我想为枚举中的每个值定义此值。 C#中是否有执行此类操作的功能?

感谢任何可以提供帮助的人!

1 个答案:

答案 0 :(得分:0)

我可能会误解你的问题;但是,您可以这样连接:

public class MyClass {
   private Dictionary<DataType, Action<object[]>> dispatcher;
   public MyClass() {
    dispatcher = new Dictionary<DataType, Action<object[]>>();
    dispatcher.Add(DataType.dateTime, InsertDateTime);
    dispatcher.Add(DataType.time, InsertTime);
    ...
    }
   //your "overload" of what to do with dateTime
   private void InsertDateTime(object[] specialValues) {
      var date = (DateTime)specialValues[0]; //assume the first param is DateTime;
      var parentId = (int)specialValues[1]; //assume the 2nd param is an int, 
      ...etc
   }
   //your "overload" for what to do with time
   private void InsertTime(object[] specialValues) {
      //do whatever special values you expect for DateType.time
   }      
   public void InsertValue(DataType dataType, params object[] specialValues) {
      //this function will cause the appropriate dataType specific Insert method to be called
      dispatcher[dataType].Invoke(specialValues);
   }
}

如果您知道每种类型的方法签名是统一的,那么这样做会更清洁,但是假设您的“特殊值”是每种类型的唯一签名,我使用了Action<object[]>,但是您可以使用{{1} }或获取更好的方法签名所需的任何内容。

不确定是否适合您要尝试的操作。开关盒的可读性可能更高。