【发布时间】:2026-02-12 00:40:02
【问题描述】:
基本上我想使用我自己的类型而不是像 int/double 这样的原始类型,但仍然传递这些原始值。比如:
interface IInt {} // My interface to represent int. If I could fake so "int" implements this, all would work.
interface IPostNumber : IInt {} // Post number is an int. But int is not type safe enough for me.
void MyFunction(IPostNumber postNumber); // My function that should accept int/IPostNumber.
MyFunction(42); // This could also work with implicit conversion, but not allowed for interfaces:(
【问题讨论】:
-
我认为您正在寻找所谓的“使用别名指令”。
-
使用 IPostNumber = System.Int32;使用 IAccountNumber = System.Int32;可以使用,但类型系统不会确保 IAccountNumber 不作为 IPostNumber 传递。而且我还想将该接口用于其他接口的东西。
-
您需要解决什么具体问题?这似乎是一种过度思考。
-
问题:为什么要使用自定义接口而不是像int、double等值类型?
标签: c# interface primitive type-safety type-alias