在Dictionary<int, object>上使用必需的属性来防止空值,可以通过以下步骤实现:
示例代码如下:
using System;
using System.Collections.Generic;
public class CustomDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
private Dictionary<TKey, Nullable<TValue>> dictionary = new Dictionary<TKey, Nullable<TValue>>();
public new void Add(TKey key, TValue value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value), "Value cannot be null.");
}
dictionary.Add(key, value);
}
public new TValue this[TKey key]
{
get
{
if (!dictionary.ContainsKey(key))
{
throw new InvalidOperationException("Value has not been set.");
}
return dictionary[key].Value;
}
set
{
dictionary[key] = value;
}
}
}
// 使用示例
public class Program
{
public static void Main(string[] args)
{
CustomDictionary<int, object> dictionary = new CustomDictionary<int, object>();
// 添加键值对
dictionary.Add(1, "Value 1");
dictionary.Add(2, "Value 2");
// 获取值
Console.WriteLine(dictionary[1]); // 输出:Value 1
Console.WriteLine(dictionary[2]); // 输出:Value 2
// 尝试获取未设置的值
try
{
Console.WriteLine(dictionary[3]);
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.Message); // 输出:Value has not been set.
}
// 尝试添加空值
try
{
dictionary.Add(4, null);
}
catch (ArgumentNullException ex)
{
Console.WriteLine(ex.Message); // 输出:Value cannot be null.
}
}
}
这样,通过自定义的Dictionary<int, object>类,我们可以在使用字典时,对必需的属性进行空值的检查和防止。
领取专属 10元无门槛券
手把手带您无忧上云