简体   繁体   English

创建分层匿名类型

[英]Create hierarchical anonymous type

Is there any way to create 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 reference delegate from itself: 例如,我们可以自己引用委托:

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

Another example, we can create generic 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 think of any ways to reference anonymous type from itself? 你能想到从自己引用匿名类型的任何方法吗?

Anonymous types in C# are immutable . C#中的匿名类型是不可变的 Therefore all of their field values must have been present before the creation of the object and will never change. 因此,所有字段值必须在创建对象之前存在并且永远不会更改。 And therefore it is impossible to have a directly circular referencing anonymous type in C#. 因此,在C#中直接循环引用匿名类型是不可能的。

Anonymous types in VB are mutable; VB中的匿名类型是可变的; you could probably figure out some way to do it in VB. 你可能想出一些在VB中做的方法。

There might be a way to make an anonymous type indirectly reference itself, by, say, containing a delegate that when invoked, returns the instance of the anonymous type. 可能有一种方法可以使匿名类型间接引用自身,例如,包含一个委托,该委托在被调用时返回匿名类型的实例。 I don't see any way off the top of my head to easily do that, but I also don't see a proof that doing so is impossible. 我没有看到任何方法轻易做到这一点,但我也没有看到证明这样做是不可能的。 Give it some thought and see what you come up with! 仔细考虑一下,看看你想出了什么!

I assume this question is for entertainment purposes only. 我认为这个问题仅用于娱乐目的。 If you want to make a circularly-referential object, please make a nominal type. 如果你想制作一个圆形参考物体,请做一个名义上的类型。

It seemed... that the C# compiler will simply refuses to infer the type recursively. 似乎...... C#编译器将拒绝递归地推断类型。 Take this sample code for example: 以此示例代码为例:

(From @Eric: Correct; the type inference engine requires that all the "input" types of a lambda be known before the "output" type of the lambda is inferred) (来自@Eric:正确;类型推理引擎要求在推断出“输出”类型的lambda之前知道lambda的所有“输入”类型)

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

This snippet fails to compile with an error that the compiler cannot infer the <T> to use with Generator<T> ... thus I think it's impossible. 这段代码无法编译,错误是编译器无法推断<T>Generator<T>一起使用...因此我认为这是不可能的。

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

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