代码之家  ›  专栏  ›  技术社区  ›  Bruno Brant

是否仍要将泛型参数默认为特定类型?

  •  15
  • Bruno Brant  · 技术社区  · 14 年前

    class Something<T = string>
    {
    }
    

    我知道这并没有很多强有力的理由,但是我想提示代码客户机他应该使用哪种类型。

    另外,我可以将泛型类型限制为 ValueType ? 我刚看到你不能,但我还是想知道为什么。有人有线索吗?

    5 回复  |  直到 14 年前
        1
  •  23
  •   Vercas    14 年前

    好吧,我想你上的是:

    class Something<T>
    {
    
    }
    

    class Something : Something<string>
    {
        // NO MORE CODE NEEDED HERE!
    }
    

    这是唯一也是最好的办法。
    Something 他真的会用 Something<string> .

        2
  •  2
  •   Donut    14 年前

    where 关键字来约束可以用作类型参数的特定类型。

    IComparable 接口:

    class Something<T> where T : IComparable
    {
    }
    

    或者,正如您所提到的,您可以约束 T where T : struct :

    class Something<T> where T : struct
    {
    }
    

    Constraints on Type Parameters 更多信息。希望这有帮助!

        3
  •  1
  •   bradenb    14 年前

    class MyGeneric<T> where T : struct
    {
        ...
    }
    
        4
  •  1
  •   Patko    14 年前

    根据 docs 你可以约束 T 使用 where 关键字

    where T: struct
    

    类声明将如下所示:

    class Something<T> where T: struct {
      ...
    } 
    

    尽管 string 不是值类型,您将无法将其与此类约束一起使用。也许 吧 IComparable 如果您还想使用 键入。

    至于指定默认类型,我认为这是不可能的。

        5
  •  0
  •   AiApaec    10 年前

    你需要一个子类。最近我需要这样的东西,这是我的解决方案:

        public abstract class MyGenericClass<T1, T2>
        {
            public abstract void Do(T1 param1, T2 param2);
        }
    
        public class Concrete : MyGenericClass<string, int?>
        {        
            public override void Do(string param1, int? param2 = null)
            {
                Console.WriteLine("param1: {0}", param1);
    
                if (param2 == null)
                    Console.WriteLine("param2 == null");
                else
                    Console.WriteLine("param2 = {0}", param2);
    
                Console.WriteLine("=============================================");
            }        
        }
    

        string param1 = "Hello";
        Concrete c = new Concrete();
        c.Do(param1);
        c.Do(param1, 123);
        c.Do(param1, (int?)null);
        /*  Result:
        param1: Hello
        param2 == null
        =============================================
        param1: Hello
        param2 = 123
        =============================================
        param1: Hello
        param2 == null
        =============================================
        */
    

    我更喜欢使用空的默认值,因为我读到: C# In Depth – Optional Parameters and Named Arguments