C# 返回动态对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9523527/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:44:01  来源:igfitidea点击:

Return dynamic object

c#asp.net

提问by TheWebGuy

I have a simple data layer routine that performs a password update, the user passes in the following:

我有一个执行密码更新的简单数据层例程,用户传入以下内容:

  • Current Password, New Password, Confirm New Password.
  • 当前密码、新密码、确认新密码。

In my data layer (proc) checks a couple things such as:

在我的数据层 (proc) 中检查几件事,例如:

  1. Is the current password correct?
  2. Is the new password and confirm password correct?
  3. Has the new password been assigned in the past?
  1. 当前密码是否正确?
  2. 新密码和确认密码是否正确?
  3. 过去是否分配过新密码?

And so on...

等等...

Now I know I can simply create a class and returned a couple booleans:

现在我知道我可以简单地创建一个类并返回几个布尔值:

public class UpdatePasswordResponse{

public bool CurrentPasswordCorrect {get;set;}
....(and so on)

}

But is there a way I can dynamically return that information to the biz layer in properties instead of creating a new class everytime (for every data layer routine)? I seem to remember thinking this was possible. I am pretty sure I read it somewhere but don't remember the syntax, can someone help me?

但是有没有一种方法可以将该信息动态返回到属性中的 biz 层,而不是每次都创建一个新类(对于每个数据层例程)?我似乎记得我认为这是可能的。我很确定我在某处读过它但不记得语法,有人可以帮助我吗?

采纳答案by Randolpho

You can do this in .NET 4 with the use of the dynamickeyword.

您可以在 .NET 4 中使用dynamic关键字来执行此操作。

The class you will want to return would be an ExpandoObject.

您要返回的类将是ExpandoObject

Basically, follow this pattern:

基本上,请遵循以下模式:

public object GetDynamicObject()
{
    dynamic obj = new ExpandoObject();
    obj.DynamicProperty1 = "hello world";
    obj.DynamicProperty2 = 123;
    return obj;
}


// elsewhere in your code:

dynamic myObj = GetDynamicObject();
string hello = myObj.DynamicProperty1;

回答by Mattias ?slund

If you just want to dynamically create a class you write:

如果你只想动态创建一个你写的类:

public object MyMethod()
{
     var result = new { Username = "my name", Password = "the password" };
     return result;
}