c# - C# 中的菱形语法

标签 c# types initialization

Java 7 现在有了这种“菱形语法”,我可以在其中执行类似 ArrayList<int> = new ArrayList<>(); 的操作

我想知道 C# 是否具有我可以利用的类似语法。
例如,我有一个类的这一部分:

class MyClass
{
    public List<double[][]> Prototypes; // each prototype is a array of array of doubles

    public MyClass()
    {
        Prototypes = new List<double[][]>; // I'd rather do List<>, in case I change the representation of a prototype later
    }
}

有谁知道这是否可行,如果可行,我该如何使用它?

最佳答案

不,没有什么比 C# 中的菱形语法更好的了。您最接近的可能是拥有这样的东西:

public static class Lists
{
    public static List<T> NewList<T>(List<T> ignored)
    {
        return new List<T>();
    }
}

然后:

public MyClass()
{
    ProtoTypes = Lists.NewList(ProtoTypes);
}

这只是对方法使用普通的泛型类型推断来获取 T。请注意,参数的 已被完全忽略 - 只有编译时类型才是重要的。

我个人认为这很丑陋,我直接使用构造函数。如果您更改 ProtoTypes 的类型,编译器会发现差异,并且根本不会花很长时间来修复它...

编辑:要考虑的两种选择:

  • 一个类似的方法,但是有一个out参数:

    public static class Lists
    {
        public static void NewList<T>(out List<T> list)
        {
            list = new List<T>();
        }
    }
    
    ...
    
    Lists.NewList(out ProtoTypes);
    
  • 相同的方法,但作为扩展方法,名称为 New:

    public static class Lists
    {
        public static List<T> New<T>(this List<T> list)
        {
            return new List<T>();
        }
    }
    
    ...
    
    ProtoTypes = ProtoTypes.New();
    

我更喜欢第一种方法:)

关于c# - C# 中的菱形语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17731423/

相关文章:

haskell - 数字类型签名

c++ - C++中的继承。为什么错了?

c++ - 使用 union 推迟成员变量构造

c# - 模棱两可的引用意见

c# - 如何将当前时间与一天中的时间进行比较

database - Oracle 数据类型列表

c# - 从 C# 中的构造函数调用实例方法

c# - mvvmcross 的 AOT 问题

c# - LINQ to Entities 而不是存储过程?

c# - 如何将属性的 .NET 反射与每个对象相关联?