我想知道是否有C#中等价于TypeScript的never类型
例如,使用TS编写以下代码会在构建时出现错误。
enum ActionTypes {
Add,
Remove
}
type IAdd = {type: ActionTypes.Add};
type IRemove = {type: ActionTypes.Remove};
type IAction = IAdd | IRemove;
const ensureNever = (action: never) => action;
function test(action: IAction) {
switch (action.type) {
case ActionTypes.Add:
break;
default:
ensureNever(action);
break;
}
}
错误信息是:类型“IRemove”的参数不能赋给类型“never”的参数。
当有人在一个文件中改变逻辑并且我想确保这个新情况在任何地方都被处理时,这非常有用。
在c#中有什么方法可以做到这一点吗?(我搜索了一下,但没有找到任何东西)
这是我目前的进展...
using System;
class Program
{
private enum ActionTypes
{
Add,
Remove
}
interface IAction {
ActionTypes Type { get; }
}
class AddAction : IAction
{
public ActionTypes Type
{
get {
return ActionTypes.Add;
}
}
}
class RemoveAction : IAction
{
public ActionTypes Type
{
get
{
return ActionTypes.Remove;
}
}
}
static void Test(IAction action)
{
switch (action.Type)
{
case ActionTypes.Add:
Console.WriteLine("ActionTypes.Add");
break;
default:
// what should I put here to be sure its never reached?
Console.WriteLine("default");
break;
}
}
static void Main(string[] args)
{
var action = new RemoveAction();
Program.Test(action);
}
}
我希望在构建时而不是运行时发现错误。