111,097
社区成员




public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/id");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{*pathInfo}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } //这里是怎么识别这个匿名类的?
);
}
}
@Html.TextBox("name", "value", new { style = "font-size:12px" })
//当Class1在另一个程序集中时
namespace MyLib
{
public class Class1
{
public string Method1(dynamic obj)
{
/* 这里将会发生异常:
“Microsoft.CSharp.RuntimeBinder.RuntimeBinderException”类型的未经处理的异常在 System.Core.dll 中发生
其他信息: “object”未包含“id”的定义
*/
return obj.id;
}
}
}
using System;
namespace Test
{
class Program
{
static void Main(string[] args)
{
//Class2的Method1成功
var c2 = new Class2();
Console.Write(c2.Method1(new { id = "object2" }));
//Class1的Method1失败
var c = new MyLib.Class1();
Console.Write(c.Method1(new { id = "object1" }));
}
}
class Class2
{
public string Method1(dynamic obj)
{
return obj.id;
}
}
}
原来如此。// 程序集1 类Class1
public void Method1(object obj)
{
var idProperty = obj.GetType().GetProperties().FirstOrDefault(p => p.Name == "id");
if (idProperty != null)
{
var id = idProperty.GetValue(obj, null);
Debug.WriteLine(string.Format("id={0}", id));
}
}
// 程序集2
void Method2()
{
var cls1 = new Class1();
var obj = new { id = "object1" };
cls1.Method1(obj);
}
[/quote]// 程序集1 类Class1
public void Method1(object obj)
{
var idProperty = obj.GetType().GetProperties().FirstOrDefault(p => p.Name == "id");
if (idProperty != null)
{
var id = idProperty.GetValue(obj, null);
Debug.WriteLine(string.Format("id={0}", id));
}
}
// 程序集2
void Method2()
{
var cls1 = new Class1();
var obj = new { id = "object1" };
cls1.Method1(obj);
}
[/quote]
你的代码确实写得没错,但你确定你运行过上面的代码吗?// 程序集1 类Class1
public void Method1(object obj)
{
var idProperty = obj.GetType().GetProperties().FirstOrDefault(p => p.Name == "id");
if (idProperty != null)
{
var id = idProperty.GetValue(obj, null);
Debug.WriteLine(string.Format("id={0}", id));
}
}
// 程序集2
void Method2()
{
var cls1 = new Class1();
var obj = new { id = "object1" };
cls1.Method1(obj);
}