我正在实现一个灵活的处理器,通过模板方法动态创建一些数据。一切正常,直到...我需要将元素添加到 ObservableCollection
并且我将包含集合的对象作为动态引用。
所以我有这个:
dynamic componentItem = Activator.CreateInstance(targetType);
targetType (UxBillingLineItem
) 包含此属性,该属性在默认构造函数中初始化:(
public ObservableCollection<UxBillingLineItem> ComponentServices { get; set; }
嵌套是有意的)
我创建一个元素以添加到此集合中:
object comp = Activator.CreateInstance(targetType);
然后我这样做来添加它:
componentItem.ComponentServices.Add(comp);
但我得到这个例外:
'System.Collections.ObjectModel.Collection.Add(UxBillingLineItem)
的最佳重载方法匹配有一些无效参数”
编辑...
我已经考虑过执行 Convert.ChangeType(comp, targetType)
但仍然返回对象,而不是 targetType 并返回相同的错误。
还查看了:
public T ConvertType<T>(object input)
{
return (T)Convert.ChangeType(input, typeof(T));
}
但在编译时仍然需要类型,而不是变量。
I'm implementing a flexible processor to dynamically create some data via a template approach. Everything working well until... I need to add elements to an ObservableCollection<item>
and I'm referencing the object containing the collection as a dynamic.
So I have this:
dynamic componentItem = Activator.CreateInstance(targetType);
targetType (UxBillingLineItem
) contains this property which is initialized in the default constructor:
public ObservableCollection<UxBillingLineItem> ComponentServices { get; set; }
(The nesting is deliberate)
I create an element to add to this collection:
object comp = Activator.CreateInstance(targetType);
Then I do this to add it:
componentItem.ComponentServices.Add(comp);
But I get this exception:
The best overloaded method match for 'System.Collections.ObjectModel.Collection<UxBillingLineItem>.Add(UxBillingLineItem)
has some invalid arguments"
Edit...
I've looked at doing Convert.ChangeType(comp, targetType)
but that still returns object, not targetType and returns the same error.
Also looked at:
public T ConvertType<T>(object input)
{
return (T)Convert.ChangeType(input, typeof(T));
}
but that still needs a type at compile time, not a variable.
发布评论
评论(2)
出现此问题的原因是您无法将
System.Object
添加到强类型ObservableCollection
。为了解决这个问题,您的 comp 变量需要输入为UxBillingLineItem
。 例如:The problem occurs because you can't add a
System.Object
to a strongly typedObservableCollection<UxBillingLineItem>
. To address this, your comp variable needs to be typed asUxBillingLineItem
. e.g.:Nicole Calinoiu 提供了最好的答案——仿制药。我修改了我的方法以使用泛型类型,一切都按预期工作。
私有列表> CreateBillingItemsFromMap>(参考RatingData ratingData、动态processMap、Hashtable propertyMap)其中T:new()
Nicole Calinoiu provided the best answer - generics. I modified my method to use a generic type and everything works as expected.
private List
<T
> CreateBillingItemsFromMap<T
>(ref RatingData ratingData, dynamic processMap, Hashtable propertyMap) where T : new()