C#使用类型参数将对象强制转换为类

绝地武士山姆

我有一个名为Property的类,该类存储一个值,如果值更改,则会引发一个事件。我要包含一个属性字典,这是另一个名为Observable的类,下面有一个示例。如何获取存储在字典中的属性的类型,以便可以修改对象?

物业类别:

public class Property<T>
{
     public T Value { get; set; }
}

可观察类:

public class Observable
{
    public readonly Dictionary<string, object> 
              Properties = new Dictionary<string, object>();

    public Property<T> Get<T>(string name)
    {
        object obj;
        Properties.TryGetValue(name, out obj);
        return (Property<T>) obj;
    }
}

编辑 这是我得到的错误-未处理的异常:System.InvalidCastException:无法将类型为“ System.String”的对象转换为类型为“ ConsoleApplication.Property`1 [System.String]”。

另外,如果我可以摆脱Get函数并将其替换为不需要知道更好的类型的东西。

更新:是否可以通过将名称与类型哈希在一起来获取类型?

弗兰克·布莱斯

编辑(用于更新的帖子):

有没有一种方法可以通过将名称与类型哈希在一起来获取类型?

这样的事情是你要去的吗?dotnetfiddle链接

public interface IProperty
{
    object Value { get; }
    Type TypeOfValue { get; }
}

public class Property : IProperty
{
    public object Value { get; set; }
    public Type TypeOfValue { get; set; }
    public override string ToString() { return TypeOfValue.FullName + ": " + Value; }
}

public class Observable
{
    public readonly Dictionary<string, Property> 
        Properties = new Dictionary<string, Property>();

    // use interface so consumer of your property can't mess with the
    // type or value stored in your dictionary within Observable
    public IProperty Get(string name)
    {
        Property obj;
        if (Properties.TryGetValue(name, out obj)){
            return obj;
        }

        // throw something which makes more sense to you
        throw new ArgumentException(name + " does not exist in the dictionary");
    }

    // sample of how you'd store these properties
    public void Set(string name, object val)
    {
        if (Properties.ContainsKey(name)){
            Properties[name].Value = val;
            Properties[name].TypeOfValue = val.GetType();
        } else {
            Properties[name] = new Property {
                Value = val,
                TypeOfValue = val.GetType()
            };
        }
    }
}

原始答案:

您可能无意中将而不是插入astring到字典中,如果是这样,问题就出在您发布的代码中,而不是在您要插入不是的地方ObservableProperty<string>stringProperty<string>

如果您不喜欢无效的强制转换异常,则有两种解决方案。

解决方案1:自定义函数引发的错误。

如果您想保留Get<T>(...)I的签名,建议您进行一些错误处理。您看到的错误是因为字典中的属性属于类型string,而不是类型Property<string>以下代码将为您提供一些可用于更多错误处理的东西。

public class Observable
{
    public readonly Dictionary<string, object> 
        Properties = new Dictionary<string, object>();

    public Property<T> Get<T>(string name)
    {
        object obj;
        if (Properties.TryGetValue(name, out obj)){
            try {
                return (Property<T>) obj;
            } catch(InvalidCastException){
                // throw something which makes more sense to you
                throw new ArgumentException("Could not cast the given object to the desired type");
            }
        }

        // throw something which makes more sense to you
        throw new ArgumentException(name + " does not exist in the dictionary");
    }
}

解决方案2:返回一般 object

public class Observable
{
    public readonly Dictionary<string, object> 
        Properties = new Dictionary<string, object>();

    public object Get(string name)
    {
        object obj;
        if (Properties.TryGetValue(name, out obj)){
            return obj;
        }

        // or do whatever you want when the given key doesn't exist.
        return null;
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将对象强制转换为C#类

在 C# 中不使用反射将对象转换为用户定义类型的类对象

将对象转换为C#类

C ++将对象强制转换为其原始类型

防止将对象强制转换为C ++以外的任何类型

使用泛型将对象强制转换为其父类型

将对象转换为作为参数传递的类类型

将对象列表转换为类的类型参数列表

无法使用输出参数将对象从DBNull强制转换为存储过程中的其他类型

将对象转换为类类型

C#将对象强制转换为存储在字符串变量中的另一种类型

将对象类型强制转换为自定义类时发生System.InvalidCastException

将对象强制转换为未知数据类型

为什么在c#中将对象强制转换为具有相同值的T类型的对象时,识别的对象不相同?

使用SSMS 2016时出错:无法将对象从DBNull强制转换为其他类型

如果将对象强制转换为实际类型,使用虚拟函数会产生任何费用吗?

不能使用 Visual Basic 代码将对象从 DBNull 强制转换为其他类型

在 C# 中,您可以将对象类型向上转换为通用“对象”的集合类型吗?

如何在不使用C#明确检查类型的情况下自动将对象转换为具体类型?

使用AutocompleteStringCollection时C#无法将对象类型数组转换为字符串类型数组

如何使用C#泛型将类的对象转换为T类型的对象?

使用熊猫python 35将对象类型列转换为float32类型

如何使用ASM将对象(对象类)动态转换为方法返回类型?

“无法将Python对象参数转换为类型'<typename>'”-使用Cython包装c ++类时出错

使用 C# 中其他类中定义的方法将对象转换为字节数组

在 TypeScript 中将对象值转换为类枚举类型

使用熊猫将对象类型列转换为数字类型

将对象强制转换为List <String>

将对象强制转换为Double []