[英]C# - Converting object to int without casting
我有一个方法,该方法根据给定的列(数据库类)返回一种对象。 但是,当我分配对象时,编译器将引发错误,提示它无法将对象类型隐式转换为int。 如何在不进行转换的情况下进行转换?
看起来更好:
this.Id = datum["Id"];
但是现在我必须包含一个强制转换,这使得代码不那么干净,更难编码:
this.Id = (int)datum["Id"];
这是我的代码:
public object this[string name]
{
get
{
object result;
if (this.Dictionary.ContainsKey(name))
{
if (this.Dictionary[name] is DBNull)
{
result = null;
}
else if (this.Dictionary[name] is byte && Meta.IsBool(this.Table, name))
{
result = (byte)this.Dictionary[name] > 0;
}
else
{
result = this.Dictionary[name];
}
}
else
{
result = default(object);
}
return result;
}
set
{
if (value is DateTime)
{
if (Meta.IsDate(this.Table, name))
{
value = ((DateTime)value).ToString("yyyy-MM-dd");
}
else if (Meta.IsDateTime(this.Table, name))
{
value = ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
}
}
if (this.Dictionary.ContainsKey(name))
{
this.Dictionary[name] = value;
}
else
{
this.Dictionary.Add(name, value);
}
}
}
您可以将索引器签名更改为:
public dynamic this[string name]
这将使转换在执行时动态化。
就个人而言,我更喜欢强制转换方法。 很明显,这可能会失败-您正在告诉编译器您有不可用的信息。
Dictionary<,>.TryGetValue
,可以利用Dictionary<,>.TryGetValue
和字典索引器的行为来更简单地编写代码:
public object this[string name]
{
get
{
object result;
if (Dictionary.TryGetValue(name, out result))
{
if (result is DBNull)
{
result = null;
}
else if (result is byte && Meta.IsBool(this.Table, name))
{
result = (byte) result > 0;
}
}
return result;
}
set
{
// TODO: Byte/bool conversions?
if (value is DateTime)
{
// Note use of invariant culture here. You almost certainly
// want this, given the format you're using. Preferably,
// avoid the string conversions entirely, but...
DateTime dateTime = (DateTime) value;
if (Meta.IsDate(this.Table, name))
{
value = dateTime.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
}
else if (Meta.IsDateTime(this.Table, name))
{
value = dateTime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
}
}
Dictionary[name] = value;
}
}
使用类Convert
:
Convert.ToInt32(datum["Id"]);
如果您不需要在代码中声明要从object
为int
,那么编程语言将无法帮助您避免错误。
C#确实具有一项功能,您可以关闭对特定变量的静态类型检查:使索引器返回dynamic
:
public dynamic this[string name]
然后您可以说:
int n = datum["Id"];
但不利的一面是,直到运行时,您才能发现这是否正确。
您可以执行扩展方法。
创建一个这样的类。
public static class ExtensionMethods
{
public static int AsInt(this object obj)
{
return (int)obj; // add additional code checks here
}
}
然后,在您的实际代码中,您所需要做的就是像这样调用扩展方法。
this.Id = datum["Id"].AsInt();
我知道这看起来与AsInt
相同,但是它发生在方法调用AsInt
下面,并且您的代码更加AsInt
易读,因为AsInt
流畅且确定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.