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

前端 未结 7 1207
忘掉有多难
忘掉有多难 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:22

    I guess I do not get why you want to have both strong types AND implicit string conversion at the same time. For me, one rules out the other.

    I tried to solve the same problem for ints (you mention int in the title, but not in the question). I found that declaring an enum gives you a type-safe integer which needs to be explicitly cast from/to int.

    Update

    Enums may not be intended for open sets, but can still be used in such a way. This sample is from a compilation experiment to distinguish between the ID columns of several tables in a database:

        enum ProcID { Unassigned = 0 }
        enum TenderID { Unassigned = 0 }
    
        void Test()
        {
            ProcID p = 0;
            TenderID t = 0; <-- 0 is assignable to every enum
            p = (ProcID)3;  <-- need to explicitly convert
    
            if (p == t)  <-- operator == cannot be applied
                t = -1;  <-- cannot implicitly convert
    
            DoProc(p);
            DoProc(t);   <-- no overloaded method found
            DoTender(t);
        }
    
        void DoProc(ProcID p)
        {
        }
    
        void DoTender(TenderID t)
        {
        }
    

提交回复
热议问题