Why can't I set properties or use attributes in C# anonymous types?

懵懂的女人 提交于 2020-01-06 19:45:10

问题


C# anonymous types seem really useful, but I've pretty immediately hit upon an application where I would like to set the property of an anonymous type, and I'd also like to be able to use attributes.

My application is a general purpose stored procedure and SQL executor, which can automatically map C# properties to SQL input and output paramaters with appropriate SqlDbType (e.g. string maps to NVARCHAR(MAX), etc.).

e.g.

    int PersonID = 1234;
    var output = new { GivenName = (string)null, FamilyName = (string)null };
    sqlExecutor.ExecSQL("SELECT @GivenName = GivenName, @FamilyName = FamilyName FROM People WHERE PersonID = @PersonID", new { PersonID }, output);
    string GivenName = output.GivenName;
    string FamilyName = output.FamilyName;

The approach works (also for stored procedures, I just used raw SQL in the above to make it clearer what I am trying to do). But I can only make it work, in exactly the form above, by using the 'bad idea' of setting the backing fields in the anonymous output object (using code in the answer by user Alex to How to set value for property of an anonymous object?).

I can't think of any other way to create such an easy to use, lightweight interface for this kind of problem. It's pretty easy to see that attributes might be useful here too, e.g. to modify the parameter mapping.

So why are anonymous types limited to no setting and no attributes? Those both seem as if they would be useful in reasonable use-cases, and as if they would be easy features to include, given that the basic anonymous type feature is already in the language.

来源:https://stackoverflow.com/questions/37752175/why-cant-i-set-properties-or-use-attributes-in-c-sharp-anonymous-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!