得到匿名类型值 [英] Get value from anonymous type

查看:126
本文介绍了得到匿名类型值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法如下:

public void MyMethod(object obj){

  // implement

}

和我叫它是这样的:

MyMethod(new { myparam= "waoww"});

那么,怎样才能实现我的MyMethod()来得到myparam价值?

So how can I implement MyMethod() to get myparam value?

修改

我用这样的:

dynamic d= obj; 
string param = d.myparam; 

但错误崛起:

'object' does not contain a definition for 'myparam' 

我也使用断点,我看到了D的myparam字符串属性。

also I use breakpoint and I see the d have myparam string property.

和有没有什么办法来检查动态类型,如果含有这样的财产:

And is there any way to check dynamic type to if contain any property like this:

if(d.contain(myparam))?

修改II

这是我的主要code:

This is my main code:

public static MvcHtmlString SecureActionLink(this HtmlHelper htmlHelper, 
         string linkText, string actionName, string controllerName, 
         object routeValues, object htmlAttributes) {


    string areaName = 
         (string)htmlHelper.ViewContext.RouteData.DataTokens["area"];

        dynamic areaObject = routeValues;

        if(areaObject != null && !string.IsNullOrEmpty(areaObject.area))
            areaName = areaObject.area;

// more
}

和称呼其为:

<p>@Html.SecureActionLink("Secure Link between Areas", "Index", "Context", 
                          new { area = "Settings" }, null)</p>

和错误是:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' does not contain a
 definition for 'area'

 Line 303:  dynamic areaObject = routeValues;
 Line 304:
 Line 305:  if(areaObject != null && !string.IsNullOrEmpty(areaObject.area))
 Line 306:      areaName = areaObject.area;
 Line 307:

 Source File: D:\Projects\MyProject\HtmlHelpers\LinkExtensions.cs    Line: 305 

修改III

这是我的HtmlHelper定义的程序集信息:

This is my AssemblyInfo of HtmlHelper definition:

[assembly: AssemblyTitle("MyProject.Presentation")]
[assembly: InternalsVisibleTo("cpanel.MyProject.dev")]

但有错误尚未:对象不包含区域的定义
我用不同的组件却怎么也有可能,当我使用断点,我可以看到我的动态 areaobject 区域名称财产,也是我能看到的价值,但错误说:对象不包含区域的定义我想不出它如何能够可能吗?

but there is an error yet: 'object' does not contain a definition for 'area' I use different assemblies but how can it possible, when I use breakpoint I can see that my dynamic areaobject have area name property and also I can see the value of that, but the error say: 'object' does not contain a definition for 'area' I can't figure it how it can be possible?

修改

我改变了装配,现在的动态类型是内部的,但之前

I change the assembly and now dynamic type is internal but the error remains as before

推荐答案

使用这样的:

string area = areaObject.GetType().GetProperty("area").GetValue(areaObject, null);

这篇关于得到匿名类型值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆