简体   繁体   中英

Get value from anonymous type

I have a method as following:

public void MyMethod(object obj){

  // implement

}

And I call it like this:

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

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

Edit

I use this:

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

but the error rise :

'object' does not contain a definition for '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))?

Edit II

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
}

and call it as:

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

And Error is:

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 

Edit III

This is my AssemblyInfo of HtmlHelper definition:

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

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?

Edit

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);

Well, you could use dynamic typing if you're using C# 4:

public void MyMethod(object obj) {
    dynamic d = obj;
    Console.WriteLine(d.myparam);
}

It does beg the question of why you're not using a named type though. Anonymous types aren't really designed to be shared among different methods like this.

EDIT: Note that if this is in a different assembly to the original code creating the object, you'll need to use [InternalsVisibleTo] as anonymous types are internal.

First off, as others have said: don't do this in the first place. That's not how anonymous types were intended to be used.

Second, if you are bent upon doing it, there are a number of ways to do so. The slow and dangerous way is to use dynamic, as others have said.

The fast and dangerous way is to use "cast by example:

static T CastByExample<T>(object obj, T example)
{ 
    return (T)obj; 
}
static void M(object obj)
{
    var anon = CastByExample(obj, new { X = 0 });
    Console.WriteLine(anon.X);  // 123
}
static void N()
{
    M(new { X = 123 });
}

is there any way to check dynamic type to if contain any property?

Use Reflection. Of course, if you are going to use Reflection then there is no need to use dynamic in the first place . You use dynamic to avoid using Reflection , so if you are going to be using Reflection anyways, you might as well just keep on using it.

It sounds like you are trying to do something that is hard to do in C#. I would reevaluate whether you want to be doing that, and if you do, whether C# is the language for you. A dynamic language like IronPython might be a better fit for your task.

Everybody says "don't do it in the first place", but this is exactly what asp.mvc does! (Don't get me wrong I don't like it myself, but if you are writing custom html helpers you want to call them the way you call the normal html helpers...)

And you can use asp.mvc to make your life easier:

public void MyMethod(object obj){
  var dic=new System.Web.Routing.RouteValueDictionary(obj);
  string param=dic["myparam"] as string;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM