I've created a custom tool for Visual Studio that runs your custom roslyn Syntax Walker to generate additional members. This is my way for emulating the lack of metaprogramming using roslyn in C#.
https://github.com/xiety/RoslynGenerator
For example, I've used it for generating Identity Value Types:
In AccountId.cs file:
[MetaIdentity("account")]
public partial struct AccountId : IIdentity
{
}
Assign RoslynGenerator as Custom Tool for this file, and it will generate AccountId.gen.cs file for you with some boilerplate code:
public partial struct AccountId
{
private const string Prefix = "account-";
private readonly string _value;
public AccountId(string value){ _value = value; }
public AccountId(long value)
: this(Prefix + value){}
public override bool Equals(object obj)
{
if (obj == null || obj.GetType() != typeof(AccountId)) return false;
return _value == ((AccountId)obj)._value;
}
public override string ToString() => _value;
public static implicit operator AccountId(string value) => new AccountId(value);
public static implicit operator string (AccountId id) => id._value;
public static bool operator ==(AccountId a, AccountId b) => a._value == b._value;
public static bool operator !=(AccountId a, AccountId b) => !(a == b);
public override int GetHashCode() => _value.GetHashCode();
}
To make this transformation RoslynGenerator finds in your project references class called MetaSyntaxWalker and runs it's Generate method dynamically passing SemanticModel and SyntaxRoot of current file.
Комментариев нет:
Отправить комментарий