Creating a hierarchical anonymous type

Is there a way to create an anonymous type that references instances of itself?

var root = new { Name = "Root", Parent = ??? };
var child = new { Name = "Child", Parent = root };
var childOfChild = new { Name = "Grand child", Parent = child };

For example, we can refer to a delegate on our own:

Action run = null;
run = () => run();

Another example: we can create a common stack of anonymous types:

static Stack<T> CreateStack<T>(params T[] values)
{
    var stack = new Stack<T>();

    foreach (var value in values)
        stack.Add(value);

    return stack;
}

Can you come up with any ways to refer to the anonymous type from yourself?

+3
source share
2 answers

It seemed that the C # compiler would simply refuse to infer the type recursively. Take this sample code, for example:

(From @Eric: That's right, type inference requires that all โ€œinputโ€ lambda types are known before the lambda output type is output)

public void Run()
{
  var k = Generator((str, parent) => new {
    Name = str,
    Parent = parent
  });
}

public Func<string, T, T> Generator<T>(Func<string, T, T> generator)
{
  return (str, obj) => generator(str, obj);
}

, <T> Generator<T>... , , .

+1

# . . , #.

VB ; , , VB.

, , , , . , , , . , !

, . - , .

+8

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


All Articles