Skip to main content
 首页 » 编程设计

c#之你如何处理对象类型切换

2024年02月23日16lovecherry

在 C# 中,问题有时会悄悄出现。通常我得到一个对象值,然后我必须为它调用“真正的”函数。像这样:

if (type==typeof(byte)) 
  val = rs.GetByte(col); 
else if (type==typeof(int)) 
  val = rs.GetInt32(col); 
... 

或

if (type==typeof(byte)) 
  Call((byte)val); 
else if (type==typeof(int)) 
  Call((int)val); 
... 

我可以在这里看到一个文本模式,但我没有想出可以一次性处理所有脏工作的解决方案。

你如何处理它?<​​/strong>你收到对象值,你必须设置它或传递它,但不是作为对象而是作为具体类型(POD、POD 和字符串的 Nullable)和。 ..?

编辑

完成示例(这个是问题的原因):

    protected IRecord ReadRecord() 
    { 
        if (!ResultSet.Read()) 
            return null; 
 
        IRecord record = CreateIRecord(); 
 
        var type = record.GetType(); 
        int column = -1; 
 
        foreach (var prop in type.GetProperties()) 
        { 
            ++column; 
            object val; 
 
            if (prop.PropertyType == typeof(byte)) 
                val = ResultSet.GetByte(column); 
            else if (prop.PropertyType == typeof(byte?)) 
                val = ResultSet.GetSqlByte(column).ToNullable(); 
            else if (prop.PropertyType == typeof(int)) 
                val = ResultSet.GetInt32(column); 
            else if (prop.PropertyType == typeof(int?)) 
                val = ResultSet.GetSqlInt32(column).ToNullable(); 
            else if (prop.PropertyType == typeof(double)) 
                val = ResultSet.GetDouble(column); 
            else if (prop.PropertyType == typeof(double?)) 
                val = ResultSet.GetSqlDouble(column).ToNullable(); 
            else if (prop.PropertyType == typeof(DateTime)) 
                val = ResultSet.GetDateTime(column); 
            else if (prop.PropertyType == typeof(DateTime?)) 
                val = ResultSet.GetSqlDateTime(column).ToNullable(); 
            else if (prop.PropertyType == typeof(string)) 
                val = ResultSet.GetString(column); 
            else 
                throw new ArgumentException("Invalid property type {0}".Expand(prop.PropertyType.ToString())); 
 
            prop.SetValue(record, val, null); 
        } 
 
        return record; 
 
 
    } 

请您参考如下方法:

您可以使用策略模式。只需将每种类型的策略放在哈希表中,然后就不需要开关了。但是,每个策略都需要一个类。如果您有复杂的逻辑,它会特别有用。

如果逻辑相当简单,您还可以使用包含委托(delegate)的哈希表。

//pseudo code 
handlers.put(typeof(int), delegate(object value) { return something.GetInt32(value); }); 
 
//like this 
var handler = handlers[type]; 
handler.Invoke(val);