Define class with itself as generic implementation. Why/how does this work?

Define class with itself as generic implementation. Why/how does this work?

问题:

I've normally been creating Prism Events used by the EventAggregator like:

public class SomeEvent : CompositePresentationEvent<SomeEventArgs> { }

public class SomeEventArgs
{
     public string Name { get; set; }
}

But while looking at a co-workers code I noticed they did:

public class SomeEvent : CompositePresentationEvent<SomeEvent>
{
     public string Name { get; set; }
}

I guess my first question is why does this even compile? It seems to me that it's implementing a class that isn't defined yet. And second, does it negatively affect the application at all, is it negligible, or better?

 

 

解答:

I guess my first question is why does this even compile?

Which rule in the spec do you believe it's violating?   没有违反编译的规则

It seems to me that it's implementing a class that isn't defined yet.

I think you'd have to specify the exact meaning of each of those terms for the statement to be judged as accurate or not. The compiler knows about CompositePresentationEvent as it's declared elsewhere (presumably) and it knows about SomeEvent because that's the class being declared. It's like having a field of type Foo within a class Foo - entirely valid.

It's also very useful to be able to do this - particularly for comparisons. For example:

public sealed class Foo : IComparable<Foo>

says that any instance of class Foo knows how to compare itself with another instance, so it can be used for sorting in a type-safe way. In the case of structs, this also allows you to reduce boxing, as calling x.CompareTo(y) won't need any boxing when x is known to be of a type which implements IComparable<> appropriately.

Note that types can get far more interestingly and confusingly recursive. Take this (slightly modified) example from my port of Protocol Buffers:

public interface IMessage<TMessage, TBuilder>
    where TMessage : IMessage<TMessage, TBuilder>
    where TBuilder : IBuilder<TMessage, TBuilder>

public interface IBuilder<TMessage, TBuilder>
    where TMessage : IMessage<TMessage, TBuilder>
    where TBuilder : IBuilder<TMessage, TBuilder>

Here, the aim is to basically end up with two types - a "message" and a "builder" so that you can always construct each from the other. For example:

public class Foo : IMessage<Foo, FooBuilder>
{
    ...
}

public class FooBuilder : IBuilder<Foo, FooBuilder>
{
    ...
}

Curiously recurring template pattern

https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern

 

 

Declaring a Class as a Member of itself

回答1

Because it's static and therefore there is only one copy of the variable instance within the AppDomain.

What you're thinking of is this:

public class Foo
{
  private Foo lol = new Foo();
}

Notice, everything here is instance, not static.

As the commenters noted (long ago), this is valid syntactically, but would result in a StackOverflowException being thrown, as the assignment requires construction, and construction creates a new assignment. One triggers the other in a cycle that ends when the call stack reaches its maximum length.

In OP's example, assignment requires construction, but the assignment is triggered by the static constructor, not the instance constructor. The static constructor only executes once within an AppDomain, in order to initialize the class' Type. It isn't triggered by instance construction, and so (in OP's example) won't result in a stack overflow.

回答2

This is a software pattern known as "Singleton".  单例就是持有了自己类型的一个静态属性

Some people frown upon the use of the pattern for more reasons than just stated in the question but for better or for worse it is a common pattern in the .NET Framework. You will find Singleton Properties (or fields) on classes that are meant to be instantiated only once. Think of a static Instance property as a global hook upon which to hang an object.

 

Can a Custom C# object contain a property of the same type as itself?

An object can indeed have a reference to an object of its own type.

This is how most Node type objects are implemented.

As for instantiation - you can pass in the Employee object to use as manager (passing in null for no manager). Constructors can have multiple overloads:

public Employee(Employee manager)
{
   this.Manager = manager;
}

 

Generic class with self-referencing type constraint

You can cast 'this' to T:

Bar((T)this);

This however will fail if you have the following:

public class MyFoo : Foo<MyFoo> { }

public class MyOtherFoo : Foo<MyFoo> { }

Because 'MyOtherFoo' is not an instance of 'MyFoo'. Take a look at this post by Eric Lippert, one of the designers of C#.

 

 

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(252)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2016-06-01 Task.ConfigureAwait
2015-06-01 新建并保存一个空的Excel
2015-06-01 创建了对嵌入的互操作程序集间接引用,无法嵌入互操作类型
2015-06-01 演练:Office 编程(C# 和 Visual Basic)
2015-06-01 C#6.0 VS2015
2015-06-01 23种设计模式
点击右上角即可分享
微信分享提示