[C#] Add Union Constructor Utility for ObjectAPI. (#6105)

* [C#] add union constructor utility.

* add union utility test.

* std::tolower -> CharToLower

* use std::transform instead

* rebase to master. and regenerate test code
This commit is contained in:
mugisoba
2021-07-27 02:01:41 +09:00
committed by GitHub
parent ac23482022
commit e77926f0ed
7 changed files with 53 additions and 9 deletions

View File

@@ -1305,19 +1305,27 @@ class CSharpGenerator : public BaseGenerator {
code += " }\n\n";
// As<T>
code += " public T As<T>() where T : class { return this.Value as T; }\n";
// As
// As, From
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
auto &ev = **it;
if (ev.union_type.base_type == BASE_TYPE_NONE) continue;
auto type_name = GenTypeGet_ObjectAPI(ev.union_type, opts);
if (ev.union_type.base_type == BASE_TYPE_STRUCT &&
ev.union_type.struct_def->attributes.Lookup("private")) {
code += " internal ";
} else {
code += " public ";
}
code += type_name + " As" + ev.name + "() { return this.As<" + type_name +
">(); }\n";
std::string accessibility =
(ev.union_type.base_type == BASE_TYPE_STRUCT &&
ev.union_type.struct_def->attributes.Lookup("private"))
? "internal"
: "public";
// As
code += " " + accessibility + " " + type_name + " As" + ev.name +
"() { return this.As<" + type_name + ">(); }\n";
// From
auto lower_ev_name = ev.name;
std::transform(lower_ev_name.begin(), lower_ev_name.end(),
lower_ev_name.begin(), CharToLower);
code += " " + accessibility + " static " + union_name + " From" +
ev.name + "(" + type_name + " _" + lower_ev_name +
") { return new " + union_name + "{ Type = " + enum_def.name +
"." + ev.name + ", Value = _" + lower_ev_name + " }; }\n";
}
code += "\n";
// Pack()