我想知道是否可以在没有拆箱线的情况下运行以下代码:-
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;
}
}
提前致谢!
理查德。
最佳答案
一些评论:
-
t.Value = (T)x;
Actor 是必要的。这是因为 t.Value
类型为 T
和 x
类型为 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/