微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

在黑暗中,.NET创建一个带有构造函数的AnonymousType,它带有三个参数:String,String,Int32.

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

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

.NET转发我:

Additional @R_582_4045@ion: 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,Count = g.Count() });

所以,我需要将每个json项目投影到一个新的{Channel = g.Key.Channel,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使用匿名类型的构造函数,请参阅IL

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐