c# - 如何在 C# 中转换传递给 Thread 的参数的数据类型

标签 c# multithreading casting

我有一个 MyFunction,它可能采用多种数据类型,它们都非常相似。我只想通过多线程将所有这些不同类型的数据传递到 MyFunction 中,并在 MyFunction 中进行类型转换。这可能吗?使用字典是个好主意吗?请指教。

Main(){
    Parallel.ForEach(objectType1, MyFunction)
    Parallel.ForEach(objectType2, MyFunction)
    Parallel.ForEach(objectType3, MyFunction)
}

MyFunction(object arg){
  Dictionary<string, object> d = (Dictionary<string, object>) arg;
  Type1 t1;
  Type2 t2;
  Type3 t3;
  if (d.Key == "Type1") {
        t1 = (Type1) d.Value;
        ProcessType1(t1);
  }
  else if (d.Key == "Type2") {
    t2 = (Type2) d.Value;
        ProcessType2(t2);
  }
  else if (d.Key == "Type3") {
    t3 = (Type3) d.Value;    
        ProcessType3(t3);
  }

}

最佳答案

你可以这样做:

MyFunction (object arg) {
    if (arg is Type1) { ProcessType1(arg as Type1); }

    else if (arg is Type2) { ProcessType2(arg as Type2); }

    else if (arg is Type3) { ProcessType3(arg as Type3); }
}

关于c# - 如何在 C# 中转换传递给 Thread 的参数的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6499799/

相关文章:

c# - Azure 离线同步。无法添加项目 "Query execution failed with result: ' MISMATCH'。”

c# - 创建 ObservableCollection<T> 类

c# - 将代码作为参数C#传递

c - 线程练习。交替打印两个不同线程的 id

c# - ServiceInterface 中的 ServiceStack Ormlite 使用

c - 是否有可能有效地并行对 4 种不同的密码模式进行暴力攻击?

c# - 从静态方法线程安全返回引用吗?

c - 取消引用 ‘void *’ 指针和转换不起作用

c - C 是否隐式且奇怪地将数组中的这个 char 转换为 int?

Swift 类型推断和类型检查问题