开发者

Ambiguous Generic restriction T:class vs T:struct

开发者 https://www.devze.com 2022-12-28 01:51 出处:网络
This code generates a compiler error that the member is already defined with the same parameter types.

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)
      开发者_Go百科  {
            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.

0

精彩评论

暂无评论...
验证码 换一张
取 消