我有一个名为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
到字典中,如果是这样,问题就出在您发布的代码中,而不是在您要插入而不是的地方。Observable
Property<string>
string
Property<string>
如果您不喜欢无效的强制转换异常,则有两种解决方案。
如果您想保留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");
}
}
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] 删除。
我来说两句