c# - 从 Dictionary<string, object> 中获取值而不拆箱?

标签 c# generics casting boxing

我想知道是否可以在没有拆箱线的情况下运行以下代码:-

t.Value = (T)x;

或者是否有其他方法可以进行这种操作?

这是完整的代码:-

public class ValueWrapper<T>
{
    public T Value { get; set; }
    public bool HasValue { get; set; }

    public ValueWrapper()
    {
        HasValue = false;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, object> myDictionary = new Dictionary<string, object>();

        myDictionary.Add("key1", 6);
        myDictionary.Add("key2", "a string");

        var x2 = GetValue<int>(myDictionary, "key1");
        if (x2.HasValue)
            Console.WriteLine("'{0}' = {1}", "key1", x2.Value);
        else
            Console.WriteLine("No value found");

        Console.ReadLine();
    }

    static ValueWrapper<T> GetValue<T>(IDictionary<string, object> dictionary, string key)
    {
        ValueWrapper<T> t = new ValueWrapper<T>();

        object x = null;
        if (dictionary.TryGetValue(key, out x))
        {
            if (x.GetType() == typeof(T))
            {
                t.Value = (T)x;
                t.HasValue = true;
            }
        }

        return t;
    }
}

提前致谢!

理查德。

最佳答案

一些评论:

  1. t.Value = (T)x;

Actor 是必要的。这是因为 t.Value类型为 Tx类型为 object . C# 的强类型特性要求您告诉编译器“看,我知道这可能不安全,但您能不能通过转换或拆箱或其他方式尝试为我做这件事?谢谢!”

2.

object x = null;
if (dictionary.TryGetValue(key, out x)) {
    if (x.GetType() == typeof(T)) {
        t.Value = (T)x;
        t.HasValue = true;
    }
}

return t;

如果 x 会怎样是派生自 T 的类的一个实例?或者如果 x是实现接口(interface)的类的实例,T是那个界面?现在,您将返回 ValueWrapper<T> 的一个实例这表明字典中没有带有键 key 的对象.我认为这与大多数人的预期非常违反直觉。

此外,如果您在 dictionary 时不打算呕吐不包含与键 key 匹配的值,我认为您应该将方法重命名为 TryGetValue , 接受 out ValueWrapper<T> 类型的参数, 并返回 bool指示成功/失败。

3.

根据您的评论,这是一个解决方案。

public interface IValueWrapper {
    object Value { get; set; }
    bool HasValue { get; set; }
}

public class ValueWrapper<T> : IValueWrapper {
    public T Value { get; set; }
    object IValueWrapper.Value { 
        get { return Value; }
        set { this.Value = (T)value; }
    }
    public bool HasValue { get; set; }

    public ValueWrapper() {
        this.HasValue = false;
    }

    public ValueWrapper(T value) {
        this.Value = value;
        this.HasValue = value != null;
    }
}

public static class DictionaryExtensions {
    public static void Add<T>(
        this IDictionary<string, IValueWrapper> dictionary,
        string key,
        T value
    ) {
        ValueWrapper<T> valueWrapper = new ValueWrapper<T>(value);
        dictionary.Add(key, valueWrapper);
    }

    public static bool TryGetWrappedValue<T>(
        IDictionary<string, IValueWrapper> dictionary,
        string key,
        out ValueWrapper<T> value
    ) {
        IValueWrapper valueWrapper;
        if (dictionary.TryGetValue(key, out valueWrapper)) {
            value = (ValueWrapper<T>)valueWrapper;
            return true;
        }
        else {
            value = null;
            return false;
        }
    }
}

用法:

var dict = new Dictionary<string, IValueWrapper>();
dict.Add("hello", 5);
ValueWrapper<int> value;
dict.TryGetWrappedValue("hello", out value);

你必须添加参数检查等。

关于c# - 从 Dictionary<string, object> 中获取值而不拆箱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3982815/

相关文章:

c# - 如何检索按钮 (MonoTouch) 上的 TouchUpInside 返回值?

c# - 如何在不知道封闭泛型类型的情况下访问泛型属性

c++ - 从结构到 LPVOID 的类型转换

c++ - 如何正确地将 time_t 转换为 long int?

c# - 用c#声明javascript变量

c# - winform 中的 OnPaint - .NET Compact Framework 3.5

c# - 向 C# 类动态添加属性

java - fetch 返回不会转换为 Record 的记录类型

generics - F# 通用记录

java - 如何将对象转换为类对象(作为参数传入) - Java