C#中的钻石语法 [英] Diamond Syntax in C#

查看:76
本文介绍了C#中的钻石语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 7现在具有此钻石语法",在这里我可以执行类似ArrayList<int> = new ArrayList<>();

Java 7 now has this "diamond syntax" where I can do things like ArrayList<int> = new ArrayList<>();

我想知道C#是否具有可以利用的相似语法.
例如,我有这部分内容:

I'm wondering if C# has a similar syntax that I can take advantage of.
For example, I have this part of a class:

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
    }
}

有人知道这是否可行吗?如果可以,我将如何使用它?

Does anyone know if this is possible, and if so, how I might go about using it?

推荐答案

不,没有什么像C#中的菱形语法那样.您可能会遇到的最接近的东西是这样的:

No, there's nothing quite like the diamond syntax in C#. The closest you could come would be to have something like this:

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

然后:

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

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

That just uses normal generic type inference for methods to get T. Note that the value of the parameter is completely ignored - it's only the compile-time type which is important.

我个人认为这很丑陋,我将直接使用构造函数.如果更改ProtoTypes的类型,则编译器会发现差异,并且完全不需要花费时间即可解决...

Personally I think this is pretty ugly, and I'd just use the constructor directly. If you change the type of ProtoTypes the compiler will spot the difference, and it won't take long at all to fix it up...

要考虑的两种选择:

  • 一种类似的方法,但是带有一个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();
    

  • 我更喜欢第一种方法:)

    I prefer the first approach to either of these :)

    这篇关于C#中的钻石语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆