You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否编写代码使Register与RegisterRestrictive仅其一调用时编译/运行失败?

关于两个泛型注册方法能否单独触发调用失败的问题

咱们先把问题里的核心代码摆出来,方便分析:

泛型方法定义

public static void Register<TInterface, TImplementation>() 
    where TImplementation : class, TInterface { }

public static void RegisterRestrictive<TInterface, TImplementation>() 
    where TInterface : class 
    where TImplementation : class, TInterface { }

合法调用示例

public interface IInterface { }
public class Implementation : IInterface { }

public void Test() 
{ 
    Register<IInterface, Implementation>(); 
    RegisterRestrictive<IInterface, Implementation>(); 
}

你的疑问是:能不能写出一段调用代码,让其中一个方法编译/运行失败,另一个正常?答案是不行,原因咱们来拆解:

  • 先看两个方法的约束差异:RegisterRestrictive多了TInterface : class的约束,而Register没有。但这里有个关键的C#规则:类(TImplementation是class)只能实现或继承引用类型——也就是说,TImplementation作为类,它要实现的TInterface只能是接口(引用类型)或者另一个类(引用类型),根本不可能是值类型(比如struct)。

  • 换句话说,哪怕Register没有TInterface : class的约束,实际能满足TImplementation : class, TInterface的TInterface必然是引用类型,自动符合RegisterRestrictive的额外约束。

那有没有反例?比如尝试让TInterface是值类型?但这样的话,TImplementation(class)根本无法实现/继承这个值类型,会直接违反两个方法里的TImplementation : TInterface约束,导致两个方法都编译失败。再比如TImplementation是struct?那两个方法的TImplementation : class约束都会触发编译错误,还是同时失败。

所以不管怎么组合,要么两个方法都能正常调用,要么两个一起失败,不存在只触发单个方法报错的场景。

内容的提问来源于stack exchange,提问作者Mardoxx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:36:48