【问题标题】:How can I supply a type in a generic method to use for casting?如何在通用方法中提供类型以用于强制转换?
【发布时间】:2021-02-05 22:58:43
【问题描述】:

我有这两种方法:

private int GetInt(string key)
{
    try
    {
        return (int)_data[key];
    } catch (KeyNotFoundException)
    {
        return 0;
    }
}
private int? GetNullableInt(string key)
{
    try
    {
        return (int?)_data[key];
    } catch (KeyNotFoundException)
    {
        return null;
    }
}

但是,我想创建一种通用方法,以防止代码重复,类似于:

private T Get<T>(string key, T type)
{
    try
    {
        return (T)_data[key];
    } catch (KeyNotFoundException)
    {
        return default(T);
    }
}

但是,我似乎没有做对。该方法可以编译,但我不知道如何调用它:

Get("myKey", typeof(int)); 

没用。

Get("myKey", int);

这将是我的偏好,但这似乎是无效的语法。

【问题讨论】:

  • 你已经接近了。 private T Get&lt;T&gt;(string key),并称之为Get&lt;int&gt;("key")
  • 如果_dataIDictionary&lt;,&gt; 你真的应该使用TryGetValue
  • @xanatos 谢谢。使用泛型,这意味着只有一个地方可以更改代码:)
  • @canton7 听起来像是对我的回答!
  • 这几乎可以肯定是一个重复,但这是一个非常基本的问题,我很难找到任何东西......

标签: c# generics


【解决方案1】:

我建议使用通用字典和 en 扩展方法。即类似:

    public static T GetOrDefault<TKey, T>(this IDictionary<TKey, T> self, TKey key)
    {
        if (self.TryGetValue(key, out var value))
        {
            return value;
        }

        return default;
    }

    public static T? GetOrNullable<TKey, T>(this IDictionary<TKey, T> self, TKey key) where T : struct
    {
        if (self.TryGetValue(key, out var value))
        {
            return value;
        }

        return null;
    }

然后这样称呼它

var dict = new Dictionary<string, int>();
var valueOrDefault = dict.GetOrDefault("test");
var valueOrNull = dict.GetOrNullable("test");

这让编译器可以推断类型参数。

如果您确实需要非通用字典或Dictionary&lt;string, object&gt;,您还需要考虑如果对象不是您请求的类型会发生什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 2019-07-18
    • 2018-08-09
    • 2021-12-16
    相关资源
    最近更新 更多