开发者

C# Using T4 to generate enums

开发者 https://www.devze.com 2023-01-19 12:53 出处:网络
In my project I\'d like to use T4 to generate my enums. To test this, I created a test project with a simple form. In this project I added a .tt file and put my code into that file.

In my project I'd like to use T4 to generate my enums. To test this, I created a test project with a simple form. In this project I added a .tt file and put my code into that file.

Everything works, but I was a little bit disappointed. I thought that when the project gets exe开发者_JAVA技巧cuted, the T4 generates the enumeration. So the enumeration is always uptodate. But this ain't the case, right? If you want the enumeration to be updated, you have to do this manually and rebuild your solution. My question is, am I correct in this one? Or did I miss something.

Second, why should I use T4 to create an enum? I mean if the enum changes I have to rebuild my solution.

EDIT: I get my enum values from a database table. The table only has 2 fields: Id and Description


To be honest I don't believe it is worth the effort. You still have to go back and update your code to handle any new values. The best thing you can do is make sure you have a default case for your switch statements.

switch (enumValue)
{
    // ...
    default:
        throw new InvalidOperationException(
            "The enum value " + enumValue + " is unhandled."
        );
}


Your table isn't an actual enum equivalent

If your table changes it's values it isn't really a good contender to become an enum now is it? C# enumerations tend to be statically defined and don't change unless there's a reason for that. And when they do, code has to adopt to this change to use additional values.

So if your application is able to change table's content than this is just a usual table.

But in case you want a generic T4 template that actually does generate enumeration with XML documentation and all I've put some effort into writing such a template. Everything is well documented in this blog post. Including template's code.


Here's an article on going the other direction (generating a c# enum from the SQL view)

http://www.olegsych.com/2008/07/t4-template-for-generating-sql-view-from-csharp-enumeration/


PLINQO is able to generated enums from one table quite easily but you'd be stuck with LINQ-TO-SQL. Good enough if you only need the generated enums though!

0

精彩评论

暂无评论...
验证码 换一张
取 消