How to programmatically insert a property into a class in the source .cs file?

I am creating an automation tool to insert properties into existing class source code. For instance. I have the source code:

public class MyClass 
{
   //class members goes here

}

I want to change him so that he becomes so

public class MyClass 
{
   //class members goes here

   public string MyProp { get; set; }
}

and save it in the same file.

The class name, property type and property name will be known in advance and can be considered operation parameters. Any idea how to do this easily? Perhaps regex replace will work for this, but I don’t know which expression to use it will be flexible, regardless of the original line of the new line, spaces and identification policies.

EDIT : what I'm looking for is just automatically generating the source code, rather than manipulating classes at runtime

+5
5

, T4 templates .

T4 - .

, .

, , .

+5

, , , . , . ( , .cs, Notepad ++). , .

string text = 
@"namespace X {
    public class MyClass {
        //Text here
    }
}";
string className = "MyClass";
string propertyType = "string";
string propertyName = "MyProperty";

string regex = string.Format(@"( *)((public?)\s*(static)?\s*class\s+{0}\s*{{)", className);
string replacement = string.Format("$1$2\r\n\r\n$1    public {0} {1} {{ get; set; }}", propertyType, propertyName);

var modified = Regex.Replace(text, regex, replacement);
Console.WriteLine(modified);

:

namespace X {
    public class MyClass {

        public string MyProperty { get; set; }
        //Text here
    }
}

: , . , + 4. - , .

+3

RunTime

, DLL , ExpandoObject, fooobar.com/questions/1149615/...

, CodeDom

+2

. , , , .

IL. ( MSIL), . , , , CodeDom.

MSIL PostSharp.Net ( ) Mono.Cecil (NB , Mono , .Net).

:

  • ( ) ,
  • , CodeDom ( CodeDom).

:

  • ( )
  • IDE
0

cog, , Ruby. cog , . ,

public class MyClass 
{
    // class members goes here

    // cog: auto-properties
}

cog ( ruby ​​ script),

embed 'auto-properties' do |c|
    "    /* whatever you return gets injected into #{c.filename} */"
end

c EmbedContext. , ,

$ cog gen
Updated src/MyClass.cs - 1st occurrence of embed 'auto-properties'

public class MyClass 
{
    // class members goes here

// cog: auto-properties {
    /* whatever you return gets injected into MyClass.cs */
// cog: }
}

, , . cog , ERB .

0

All Articles