ISO C++

 1}

執行結果
(原創) 一個C++能跑的泛型,但在C#卻不能跑 (C/C++) (template) (.NET) (C#) (C++/CLI)Class1's func1
(原創) 一個C++能跑的泛型,但在C#卻不能跑 (C/C++) (template) (.NET) (C#) (C++/CLI)Class2's func1

若使用C++/CLI,也是可以實現
 1}

執行結果
(原創) 一個C++能跑的泛型,但在C#卻不能跑 (C/C++) (template) (.NET) (C#) (C++/CLI)Class1's func1
(原創) 一個C++能跑的泛型,但在C#卻不能跑 (C/C++) (template) (.NET) (C#) (C++/CLI)Class2's func1

若用C#,以下代碼無法compile成功
 1(原創) 一個C++能跑的泛型,但在C#卻不能跑 (C/C++) (template) (.NET) (C#) (C++/CLI)using System;
 2(原創) 一個C++能跑的泛型,但在C#卻不能跑 (C/C++) (template) (.NET) (C#) (C++/CLI)
 3}

C#無法compile成功
錯誤訊息為
Error 1 The call is ambiguous between the following methods or properties: 'Interface1.func1()' and 'Interface2.func1()' D:\__Clare\CSharp\CSharpLab\Class3.cs 43 5 CSharpLab

Error 2 The type 'Interface1' must be convertible to 'Interface2' in order to use it as parameter 'T' in the generic type or method 'Generic1<T>' D:\__Clare\CSharp\CSharpLab\Class3.cs 52 24 CSharpLab

Error 3 The type 'Interface2' must be convertible to 'Interface1' in order to use it as parameter 'T' in the generic type or method 'Generic1<T>' D:\__Clare\CSharp\CSharpLab\Class3.cs 55 15 CSharpLab

Error1我能理解為什麼不能過,不過並非我故意惡搞,因為實務上的確愈到這樣的需求...
Error2和Error3則真的無法理解了..

看來C#的泛型和C++泛型差異頗大...

請各位指點,該怎麼改才好,改了兩天想不出來...。

<06/16/2007>感謝hyifeng多次的指點,C#的Generics寫法如下
 1}

之前C#寫法,主要錯誤為
(原創) 一個C++能跑的泛型,但在C#卻不能跑 (C/C++) (template) (.NET) (C#) (C++/CLI)public class Generic1<T> : IGeneric where T : Interface1, Interface2
我以為是T可以是Interface1 OR Interface2,但實際上是T必須同時implement Interface1 AND Interface2,所以在C#須將相同的Interface提升至InterfaceBase,利用類似多型的方式來處理。

相关文章:

  • 2021-11-06
  • 2021-12-28
  • 2021-10-05
  • 2022-02-20
  • 2022-01-18
  • 2021-09-18
  • 2022-01-02
猜你喜欢
  • 2022-01-31
  • 2021-12-13
  • 2021-07-28
  • 2021-11-25
  • 2021-05-24
  • 2022-02-04
  • 2021-06-21
相关资源
相似解决方案