不明确的通用限制T:class vs T:struct [英] Ambiguous Generic restriction T:class vs T:struct

查看:63
本文介绍了不明确的通用限制T:class vs T:struct的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码会生成一个编译器错误,表示该成员已经使用相同的参数类型定义。

  private T GetProperty< T>(Func< Settings,T> GetFunc)其中T:class 
{
试试
{
return GetFunc(Properties.Settings.Default);
}
catch(异常异常)
{
SettingReadException(this,exception);
返回null;
}
}

私有可扩展? GetProperty< TNullable>(Func< Settings,TNullable> GetFunc)其中TNullable:struct
{
try
{
return GetFunc(Properties.Settings.Default);
}
catch(Exception ex)
{
SettingReadException(this,ex);
返回新的Nullable< TNullable>();


$ / code $ / pre

有没有干净的解决方法?

解决方案

通用类型约束不能用于重载解析,但实际上并不需要为此重载方法。只需使用 default 而不是 null

  private T GetProperty< T>(Func< Settings,T> GetFunc)
{
try
{
return GetFunc(Properties.Settings.Default) ;
}
catch(异常异常)
{
SettingReadException(this,exception);
return default(T);
}
}

哦,我已经逐字复制了您的代码,但不要像这样吞下一般的 Exception 。捕获实际期望可能引发的特定异常。您不希望此代码无意中吞咽 OutOfMemoryException BadImageFormatException 实例。


This code generates a compiler error that the member is already defined with the same parameter types.

   private T GetProperty<T>(Func<Settings, T> GetFunc) where T:class
    {
        try
        {
            return GetFunc(Properties.Settings.Default);
        }
        catch (Exception exception)
        {
            SettingReadException(this,exception);
            return null;
        }
    }

    private TNullable? GetProperty<TNullable>(Func<Settings, TNullable> GetFunc) where TNullable : struct
    {
        try
        {
            return GetFunc(Properties.Settings.Default);
        }
        catch (Exception ex)
        {
            SettingReadException(this, ex);
            return new Nullable<TNullable>();
        }
    }

Is there a clean work around?

解决方案

Generic type constraints can't be used for overload resolution, but you really don't need an overloaded method for this. Just use default instead of null:

private T GetProperty<T>(Func<Settings, T> GetFunc)
{
    try
    {
        return GetFunc(Properties.Settings.Default);
    }
    catch (Exception exception)
    {
        SettingReadException(this,exception);
        return default(T);
    }
}

Oh, and I've copied your code verbatim, but please don't swallow the general Exception like this. Catch the specific exception that you actually expect might be thrown. You don't want this code inadvertently swallowing OutOfMemoryException or BadImageFormatException instances.

这篇关于不明确的通用限制T:class vs T:struct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆