C# 从匿名类型获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9750078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get value from anonymous type
提问by Saeid
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?
那么我该如何实现MyMethod()以获取 myparam 值呢?
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.
我也使用断点,我看到 d 有 myparam 字符串属性。
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:
这是我的 HtmlHelper 定义的 AssemblyInfo:
[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 areaobjecthave areaname 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?
但还有一个错误:'object' does not contain a definition for 'area'我使用不同的程序集,但怎么可能,当我使用断点时,我可以看到我的动态areaobject具有areaname 属性,并且我可以看到它的值,但错误说:'object' does not contain a definition for 'area'我想不通它怎么可能呢?
Edit
编辑
I change the assembly and now dynamic type is internal but the error remains as before
我更改了程序集,现在动态类型是内部的,但错误仍然像以前一样
采纳答案by Saeid
Use this one:
使用这个:
string area = areaObject.GetType().GetProperty("area").GetValue(areaObject, null);
回答by Jon Skeet
Well, you could use dynamic typing if you're using C# 4:
好吧,如果您使用的是 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.
编辑:请注意,如果这与创建对象的原始代码位于不同的程序集中,则您需要使用[InternalsVisibleTo]匿名类型是内部的。
回答by Eric Lippert
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.
使用反射。当然,如果您打算使用 Reflection,那么首先就不需要使用 dynamic。您使用 dynamic 来避免使用 Reflection,所以如果您无论如何都打算使用 Reflection,那么您不妨继续使用它。
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.
听起来您正在尝试做一些在 C# 中很难做到的事情。我会重新评估您是否愿意这样做,如果愿意,C# 是否适合您。像 IronPython 这样的动态语言可能更适合您的任务。
回答by Nadav
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...)
每个人都说“首先不要这样做”,但这正是 asp.mvc 所做的!(别误会我自己不喜欢它,但是如果您正在编写自定义 html 助手,您想像调用普通 html 助手一样调用它们......)
And you can use asp.mvc to make your life easier:
你可以使用 asp.mvc 让你的生活更轻松:
public void MyMethod(object obj){
var dic=new System.Web.Routing.RouteValueDictionary(obj);
string param=dic["myparam"] as string;
}

