is there some way to autogenerate the obvious 2-param constructor for this class in visual studio?
class Thing {
public readonly string a;
public readonly Object b;
}
I gu开发者_Python百科ess you're supposed to use the:
new Thing { a = ..., b = ... }
syntax in such cases, but that won't work with readonly fields as above. Another plus of having a constructor is that you can't forget a field.
There is, Resharper supports this functionality. You choose the "generate constructor", pick the fields you want included and you've got your constructor.
Sorry for a post that's not helpful at all, but I just couldn't resist.
I'm afraid that by using things like T4 templates, you'll (probably) lose IntelliSense, which may not be a price you wanted to pay. You could probably write a VS.NET macro to auto-generate code of the constructor (I believe the code model should give you enough information to do that).
Now, here is the useless part of the post - perhaps you could try another .NET language if you're annoyed with the unnecesary verbosity of C#. In F#, you can write implicit constructors and their parameters automatically become (readonly) fields:
type Thing(a:string, b:Object) =
// members can use 'a' and 'b' directly - here is one example:
member this.GetInfo() =
"Some info: " + a + (b.ToString())
In a real-world scenario, you probably wouldn't need to specify the types, because F# could infer them automatically based on the later usage. Experimenting with F# isn't as difficult if you're already familiar with .NET libraries.
You may want to look at T4 templates. It would be fairly simple to write a template which iterates a list of the readonly property names and types and creates the necessary code for the properties and constructor.
T4 templates are built into Visual Studio. Check out Scott Hanselman's blog about T4 templates for more detail.
There are other products which can automate this kind of refactoring. Resharper is one of these, but it is not free.
精彩评论