小编Dus*_*oed的帖子

C#Reflection - 对象与目标类型不匹配

我正在尝试使用propertyInfo.SetValue()方法使用反射设置对象属性值,并且我得到异常"对象与目标类型不匹配".它真的没有意义(至少对我来说!)因为我只是想在一个带有字符串替换值的对象上设置一个简单的字符串属性.这是一个代码片段 - 它包含在一个递归函数中,所以有更多的代码,但这是胆量:

PropertyInfo fieldPropertyInfo = businessObject.GetType().GetProperties().FirstOrDefault(f => f.Name.ToLower() == piecesLeft[0].ToLower());
businessObject = fieldPropertyInfo.GetValue(businessObject, null);

fieldPropertyInfo.SetValue(businessObject, replacementValue, null);
Run Code Online (Sandbox Code Playgroud)

我已经通过执行此比较验证了"businessObject"和"replacementValue"都是相同的类型,返回true:

businessObject.GetType() == replacementValue.GetType()
Run Code Online (Sandbox Code Playgroud)

c# reflection

21
推荐指数
3
解决办法
5万
查看次数

如何使用反射将新项添加到集合中

我正在尝试使用反射将未知对象添加到未知的集合类型,并且当我实际执行"添加"时我得到一个异常.我想知道是否有人可以指出我做错了什么或另类?

我的基本方法是迭代通过反射检索的IEnumerable,然后将新项添加到辅助集合中,我稍后可以将其用作替换集合(包含一些更新的值):

IEnumerable businessObjectCollection = businessObject as IEnumerable;
Type customList = typeof(List<>)
       .MakeGenericType(businessObjectCollection.GetType());
var newCollection = (System.Collections.IList)
          Activator.CreateInstance(customList);

foreach (EntityBase entity in businessObjectCollection)
{
// This is the area where the code is causing an exception
    newCollection.GetType().GetMethod("Add")
         .Invoke(newCollection, new object[] { entity });
}
Run Code Online (Sandbox Code Playgroud)

例外是:

"Eclipsys.Enterprise.Entities.Registration.VisitLite"类型的对象无法转换为"System.Collections.Generic.List`1 [Eclipsys.Enterprise.Entities.Registration.VisitLite]"类型.

如果我使用这行代码Add(),我得到一个不同的例外:

newCollection.Add(entity); 
Run Code Online (Sandbox Code Playgroud)

例外是:

值""不是"System.Collections.Generic.List`1 [Eclipsys.Enterprise.Entities.Registration.VisitLite]"类型,并且不能在此通用集合中使用.

.net c# reflection

3
推荐指数
1
解决办法
2388
查看次数

为什么Handlebarsjs模板缺少jquery移动CSS样式?

我在一个jquery移动页面中使用Handlebarsjs,当我从服务器发回数据时,它被插入到模板中......但是没有一个jquery移动CSS样式应用于模板内的代码.

我的模板看起来像这样:

            <script id="card_list_template" type="text/x-handlebars-template">
            {{#each this}}
            <li>
                <a href="#">
                    <img src="{{path}}" />
                    <h3>{{first_name}}&nbsp;{{last_name}}</h3>
                    <p>Card Owner:&nbsp;{{user_id}}</p>
                </a>
            </li>
            {{/each}}
        </script>
Run Code Online (Sandbox Code Playgroud)

上面的代码块插入到这个无序列表中:

<ul id="search_results" data-role="listview" data-theme="a">

data-role ="listview"应该将某种样式应用于列表项,但它不适用于通过模板生成的项.

jquery jquery-mobile handlebars.js

2
推荐指数
1
解决办法
1468
查看次数

标签 统计

c# ×2

reflection ×2

.net ×1

handlebars.js ×1

jquery ×1

jquery-mobile ×1