gpt4 book ai didi

c# - 创建一个新的 AnonymousType 实例

转载 作者:行者123 更新时间:2023-11-30 12:23:25 26 4
gpt4 key购买 nike

我正在尝试创建一个 AnonymousType 实例,如下所示:

new { Channel = g.Key.Channel, Comment = g.Key.Comment, Count = g.Count() }

在黑暗中,.NET 创建了一个 AnonymousType,其构造函数采用三个参数:String、String、Int32

为了创建这个匿名类型 T 的新实例,我这样做:

object[] args = new object[3];
args[0] = "arg1";
args[1] = "arg2";
args[2] = 200;
(T)Activator.CreateInstance(typeof(T), args);

.NET 抛弃了我:

Additional information: Constructor not found in '<>f__AnonymousType2`3[[System.String, ...],[System.String, ...],[System.Int32, ...]]'.

我不知道为什么 CreateInstance 试图调用像 [[],[],[]] 这样的构造函数!

范围

真正的范围有点难以解释:

我已经创建了一个 Linq 提供程序。此提供程序将 Linq 语句翻译成我的服务器方法。当我收到 json 信息时,我需要将此信息投影到用户指定的任何类型。在这种情况下:

var enumerable = UIContainer.UIController.Instance.getDigitalInputs()
.GroupBy(di => new { Channel = di.Channel, Comment = di.Comment })
.Select(g => new { Channel = g.Key.Channel, Comment = g.Key.Comment, Count = g.Count() });

因此,我需要将每个 json 项目投影到 new { Channel = g.Key.Channel, Comment = g.Key.Comment, Count = g.Count() })。最后我需要创建这个匿名类型的实例。

所以:

// make the HTTP request
IRestResponse response = (IRestResponse) this.client.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);

if (((int)response.StatusCode) >= 400) {
throw new ApiException (response.StatusCode, "Error calling Search: " + response.Content, response.Content);
}

Newtonsoft.Json.Linq.JArray feeds = Newtonsoft.Json.Linq.JArray.Parse(response.Content);
if (feeds.Any())
{
PropertyDescriptorCollection dynamicProperties = TypeDescriptor.GetProperties(feeds.First());
foreach (dynamic feed in feeds)
{
object[] args = new object[dynamicProperties.Count];
int i = 0;
foreach (PropertyDescriptor prop in dynamicProperties)
{
args[i++] = prop.GetValue(feed);
}
//args[0] = "";
//args[1] = "";
//args[2] = 2;

yield return (T)Activator.CreateInstance(typeof(T), args);
}
}

最佳答案

不确定从哪里获得 T,但是如果您使用来自先前变量的匿名类型,代码可以正常工作:

var x = new { Channel = "Channel", Comment = "Comment", Count = 1 };

object[] args = new object[3];
args[0] = "arg1";
args[1] = "arg2";
args[2] = 200;
var y = Activator.CreateInstance(x.GetType(), args);

(回复 Luaan:.NET uses a constructor for anonymous types,see the IL:)

.method public hidebysig specialname rtspecialname 
instance void .ctor(!'<Channel>j__TPar' Channel,
!'<Comment>j__TPar' Comment,
!'<Count>j__TPar' Count) cil managed

关于c# - 创建一个新的 AnonymousType 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36908078/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com