简体   繁体   English

C#typedef泛型

[英]C# typedef generics

I am using a shorthand version for a class, which looks like this: 我正在使用类的速记版本,如下所示:

using NodeSteps = Tuple<Node, int>;

Node is a class defined by myself. Node是我自己定义的类。 This works fine usually, but the problem here is, is that Node is a generic requiring a struct. 这通常很好,但问题是,Node是一个需要结构的泛型。

My questions are as follows: 我的问题如下:

1. How are these typedefs called in C#. 1.如何在C#中调用这些typedef。 I know they are not exactly typedefs, but it was the most similar thing I could think of. 我知道它们并不完全是typedef,但它是我能想到的最相似的东西。

2. How can I make a generic version? 2.我如何制作通用版本?

using NodeSteps<T> = Tuple<Node<T>, int>;

I noticed this is not the way to do it. 我注意到这不是这样做的方法。 I also would like to specify T is a struct. 我也想指定T是一个结构。

Use 采用

class NodeSteps<T> : Tuple<Node<T>, int>
{
}

This is the closest equivalent to a typedef I know of. 这是我所知道的typedef最接近的等价物。 If there are any non-default constructors, you would need to declare them, though. 如果有任何非默认构造函数,则需要声明它们。

  1. They are called aliases. 它们被称为别名。

  2. No, this isn't possible. 不,这是不可能的。 C# Language spec: C#语言规范:

Using aliases can name a closed constructed type, but cannot name an unbound generic type declaration without supplying type arguments. 使用别名可以命名一个封闭的构造类型,但不能在不提供类型参数的情况下命名未绑定的泛型类型声明。

Therefore, using x<T> = List<T> or something similar isn't possible. 因此, using x<T> = List<T>或类似的东西是不可能的。

You may use a class (see the other answers(s)) instead. 您可以使用课程(请参阅其他答案)。

This is covered in section 9.4.1 of the C# Language spec. 这将在C#语言规范的第9.4.1节中介绍。

Using aliases can name a closed constructed type, but cannot name an unbound generic type declaration without supplying type arguments. 使用别名可以命名一个封闭的构造类型,但不能在不提供类型参数的情况下命名未绑定的泛型类型声明。

This is called alias and can not be generic, but right hand of the using can be generic 这称为别名,不能是通用的,但使用的右手可以是通用的

using ListOfInts = List<int>

is valid 已验证

using NodeSteps = Tuple<Node, int>;

is not the equivalent of a typdef but just an alias to that class. 不是typdef的等价物,而只是该类的别名 It's designed to work around namespace collisions without having to use the whole namespace. 它旨在解决命名空间冲突,而无需使用整个命名空间。 What I would do is define a new class: 我要做的是定义一个新类:

public class NodeSteps<T> : Tuple<Node<T>, int> where t: struct
{
}

This works: 这有效:

namespace Test1
{
    class Node<T>
    {
        public T Test()
        {
            return default(T);
        }
    }
}

namespace Test1
{
    using NodeSteps = System.Tuple<Node<string>, int>;

    public class Class1
    {
         public static void Main()
         {
            NodeSteps t1 = new NodeSteps(new Node<string>(), 10);

            t1.Item1.Test();
         }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM