C # typedef generics

I am using an abridged version for a class that looks like this:

using NodeSteps = Tuple<Node, int>; 

Node is a class defined by me. This works fine, but the problem here is that Node is a general framework requirement.

My questions are as follows:

1. How these typedefs are called in C #. I know that they are not completely typed, but it was the most similar that I could think of.

2. How can I create a generic version?

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

I noticed that this is not a way to do this. I would also like to indicate that T is a structure.

+6
source share
5 answers
  • They are called pseudonyms.

  • No, It is Immpossible. C # language specification:

Using aliases can call a private configured type, but cannot call an unrelated generic type declaration without providing type arguments.

Therefore, using x<T> = List<T> or something similar is not possible.

You can use a class instead (see other answers).

+7
source

Using

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

This is the closest typedef equivalent I know. If there are any non-default constructors, you will need to declare them.

+7
source

This is described in section 9.4.1 of the C # language specification.

Using aliases can call a private constructed type, but cannot call an unbound generic type without supplying type arguments.

This is called an alias and may not be common, but the right-hand use may be common

 using ListOfInts = List<int> 

really

+5
source
 using NodeSteps = Tuple<Node, int>; 

is not the equivalent of typdef , but simply an alias of this class. It is designed to work around namespace conflicts without using the entire namespace. What I would do is define a new class:

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

It 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(); } } } 
0
source

Source: https://habr.com/ru/post/957427/


All Articles