Aliasing in .NET
Is it possible to create an alias to existing types and use that alias through out the project?
For example, create
CustomerID = System.UInt32
and use CustomerID as a datatype?
Version : .NET Framework 4.0
(With the "using" keyword we would be able to create an alias, but it is开发者_StackOverflow社区 not useful as it does not work across files.)
Any other ideas?
I believe the correct answer to this question is:
No, that's (unfortunately?) not possible. :(
Edit 1: However, you can (kind of) simulate this by making your own struct
, and providing implicit conversions to/from the type you want. It's not exactly magical but it might work, depending on the situation.
Edit 2: I haven't ever used this feature before, but type forwarding might be helpful. It only forwards to another entire assembly, though, so it probably won't work for simple cases.
This doesn't seem possible. However, for which reason do you want to do this?
If your reason is readability, consider the following:
You can already use your identifiers to indicate it is e.g. a customerID
. What you are essentially doing when trying to rename UInt32
to CustomerID
is making it look like a new type. Only when a type needs additional behavior or values it is useful to consider it a 'new' type. If you ever developed in C++, you can appreciate the convention caused by not allowing this in C#. You know what to expect from a UInt32
.
If your reason is preparing yourself for changes:
E.g. suppose after some time you decide you also want to support negative ID's. This should be solved by encapsulating this possible expected behavior in a new type. So no renaming is necessary.
精彩评论