需要在方法中将某些内容转换为类型参数
本文关键字:转换 类型参数 方法 | 更新日期: 2023-09-27 18:34:40
我需要能够确定我从缓存中获取的项目是否可以强制转换为我传递给我的方法的对象的类型,以便在该项目不是该类型的有效实例时,我可以从缓存中删除该项目。
以下是我失败的尝试:
Get(dataCache, "cachedItemLabel", myObject);
public static object Get(DataCache dataCache, string label, object obj)
{
try
{
//return (obj)dataCache.Get(label);
//return typeof(obj)dataCache.Get(label);
//return dataCache.Get(label) as typeof(obj);
}
catch (DataCacheException)
{
dataCache.Remove(label);
}
return null;
}
上面的代码会导致以下异常:
return dataCache.Get(label) as typeof(obj);
结果为"预期类型">
return typeof(obj)dataCache.Get(label);
结果为 " ;意料之中">
return (obj)dataCache.Get(label);
结果为"找不到类型或命名空间名称'obj'">
使用 (Object( 强制转换对象。
public static object Get(DataCache dataCache, string label, object obj)
{
try
{
return (object)dataCache.Get(label);
}
catch (DataCacheException)
{
dataCache.Remove(label);
}
return null;
}
如果可能的话,你应该只使用泛型,这样你就可以实际将返回的值键入到指定的类型,并且很容易检查对象是否属于该类型:
public static object Get<T>(DataCache dataCache, string label)
{
try
{
object value = dataCache.Get(label);
if (value is T)
return (T)value;
else
{
dataCache.Remove(label);
return null;
}
}
catch (DataCacheException)
{
dataCache.Remove(label);
return null;
}
}
接下来,与其传入某种其他类型的对象,不如让此方法的实现以及调用方传入确定值类型应该是什么的Type
对象。 这使得实现需要做更多的工作,现在必须再次返回object
:
public static object Get(DataCache dataCache, string label, Type type)
{
try
{
object value = dataCache.Get(label);
if (value != null && type.IsAssignableFrom(value.GetType()))
return value;
else
{
dataCache.Remove(label);
return null;
}
}
catch (DataCacheException)
{
dataCache.Remove(label);
return null;
}
}
最后,我们得到您选择的签名,在其中传递某种类型的实例,并且您希望确保返回的对象属于可分配给该对象的类型的类型。 这是可行的,但特别糟糕的做法,所以你几乎肯定应该使用第二个选项,如果不是第一个选项的话:
public static object Get(DataCache dataCache, string label, object typeObject)
{
try
{
Type type = typeObject.GetType();
object value = dataCache.Get(label);
if (value != null && type.IsAssignableFrom(value.GetType()))
return value;
else
{
dataCache.Remove(label);
return null;
}
}
catch (DataCacheException)
{
dataCache.Remove(label);
return null;
}
}
看起来您的问题来自尝试将您的类型转换为obj
而不是object
好消息是,你甚至不必投掷它。
public static object Get(DataCache dataCache, string label, object obj)
{
try
{
return dataCache.Get(label);
}
catch (DataCacheException)
{
dataCache.Remove(label);
}
return null;
}