问题:无法访问对象的某个属性

原因1:对象被cast成object,所以当然找不到对应的属性。这类问题多出在asp.net mvc 动态属性上,比如:

ViewBag.UserName = new { FirstName = “james”, MiddleName = “T”, LastName = “K” };

前端mvc直接调用@ViewBag.UserName.FirstName

提示如标题的异常提示。

解决办法:新增个扩展方法

public static ExpandoObject ToExpando(this object anonymousObject)
{
IDictionary<string, object> anonymousDictionary = new RouteValueDictionary(anonymousObject);
IDictionary<string, object> expando = new ExpandoObject();
foreach (var item in anonymousDictionary)
expando.Add(item);
return (ExpandoObject)expando;
}

然后把控制器代码改为

ViewBag.UserName = new { FirstName = “james”, MiddleName = “T”, LastName = “K” }.ToExpando();

前端调用@ViewBag.UserName .FirstName即可正常显示了。

 

原因2:对象的属性是Internal的,无法跨Assembly访问,解决办法,设置InternalsVisibleTo.

当前程序集的AssemblyInfo.cs中加上

[assembly: InternalsVisibleTo("ClassLibrary1")] 

指定对指定程序集可见即可。