【发布时间】:2023-03-17 13:38:01
【问题描述】:
我想知道是否可以运行以下代码但没有拆箱行:-
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;
}
}
提前致谢!!
理查德。
【问题讨论】:
-
不,如果您的
object是盒装值类型,则需要将其拆箱。您是否有理由避免拆箱? -
主要是为了性能,因为我的项目中此代码与其他东西一起使用,拆箱将执行时间从 ~200ms 增加到 ~1700ms。这仍然可以接受,我只是想知道是否有替代方案。
-
这种急剧的性能下降极不可能是由于拆箱造成的。使用分析器确定真正的瓶颈是什么。
标签: c# generics casting boxing