Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

c# 9.0 - c# 9.0 records - reflection and generic constraints

Two questions regarding the new records feature :

  1. How do I recognize a record using reflection ? looking [here][1] maybe there is a way to detect the EqualityContract but I am not sure if that is the way to go ?

  2. Is it possible to have a generic constraint that a generic type is a record ? that is if it is possible to indicate that type parameter T must be a record class using a constraint ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. How do I recognize a record using reflection ?

If you try record classes in sharplab.io you'll see that record classes are usual classes that implement IEquatable<T> interface and contain additional members that are used to compare and clone instances of the record class. There is no special attributes that indicate that the class is a record class.

So I guess that there is no way to determine if a class is a record class using reflection.

looking here maybe there is a way to detect the EqualityContract but I am not sure if that is the way to go ?

It is possible to determine using reflection if a class has such property, but this is not a 100% guarantee that the class with such property is a record class.


  1. Is it possible to have a generic constraint that a generic type is a record ? that is if it is possible to indicate that type parameter T must be a record class using a constraint ?

It is not possible.

  1. Records proposal page does not contain any information about specifying that a generic type parameter T must be a record class.
  2. If you read discussion under this comment at Champion records page you'll learn that there is no way to specify something like where T : record in C# 9. Moreover there are plans to eliminate any meaningful semantic difference between a record and a class in C# 10. So that records' features like with will be available for classes too. Adding record constraint will make this goal not achievable.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...