问题
I'm trying to create an AnonymousType instance looks like:
new { Channel = g.Key.Channel, Comment = g.Key.Comment, Count = g.Count() }
On the dark, .NET creates an AnonymousType with a constructor that takes three arguments: String, String, Int32
.
In order to create a new instance of this anonymous type, T, I do:
object[] args = new object[3];
args[0] = "arg1";
args[1] = "arg2";
args[2] = 200;
(T)Activator.CreateInstance(typeof(T), args);
.NET dumps me:
Additional information: Constructor not found in '<>f__AnonymousType2`3[[System.String, ...],[System.String, ...],[System.Int32, ...]]'.
I don't know why CreateInstance
is trying to call a constructor like [[],[],[]]!
Scope
The real scope is a bit more hard to explain:
I've created a Linq provider. This provider translates Linq sentences to my server methods. When I receive json information I need to project this information to whichever Type user has specified. In this case:
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() });
So, I need to project each json item to a new { Channel = g.Key.Channel, Comment = g.Key.Comment, Count = g.Count() })
. At the end I need to create an instance of this anonymous type.
So:
// 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);
}
}
回答1:
Not sure where you obtain T
, but the code works fine if you use the anonymous type from the previous variable:
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);
(And in to reply to 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
来源:https://stackoverflow.com/questions/36908078/create-a-new-anonymoustype-instance