Is there a way to define C# strongly-typed aliases of existing primitive types like `string` or `int`?

前端 未结 7 1212
忘掉有多难
忘掉有多难 2021-02-18 18:52

Perhaps I am demonstrating my ignorance of some oft-used feautre of C# or the .NET framework, but I would like to know if there is a natively-supported way to create a type alia

7条回答
  •  旧巷少年郎
    2021-02-18 19:21

    Some background on why string is sealed:

    From http://www.code-magazine.com/Article.aspx?quickid=0501091 :

    Rory: Hey Jay, you mind if I ask you a couple questions? I'm already curious about some things. First of all, and this was brought up at one of the MSDN events I did this week, why is String sealed? Note: for VB.NET programmers, Sealed = NotInheritable.

    Jay: Because we do a lot of magic tricks in String to try and make sure we can optimize for things like comparisons, to make them as fast as we possibly can. So, we're stealing bits off of pointers and other things in there to mark things up. Just to give you an example, and I didn't know this when I started, but if a String has a hyphen or an apostrophe in it [then] it sorts differently than if it just has text in it, and the algorithm for sorting it if you have a hyphen or an apostrophe if you're doing globally-aware sorting is pretty complicated, so we actually mark whether or not the string has that type of behavior in it.

    Rory: So, what you're saying is that in the string world, if you didn't seal String there would be a whole lot of room for wreaking a lot of havoc if people were trying to subclass it.

    Jay: Exactly. It would change the entire layout of the object, so we wouldn't be able to play the tricks that we play that pick up speed.

    Here is the CodeProject article that you probably have seen before:

    http://www.codeproject.com/KB/cs/expandSealed.aspx

    So yeah, implicit operator is your only solution.

提交回复
热议问题