Skip to content

Instantly share code, notes, and snippets.

@Thaina
Last active September 3, 2019 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Thaina/eaffbfbafcf572e8e05d99df55aa3101 to your computer and use it in GitHub Desktop.
Save Thaina/eaffbfbafcf572e8e05d99df55aa3101 to your computer and use it in GitHub Desktop.
T4 file for generate common operator on C# object
<#@ output extension=".cs" #>
class ObjectProxyOperator
{
<#
{
var types = new[]{ "sbyte","byte","short","ushort","int","uint","long","ulong","float","double","decimal" };
foreach(var pair in new System.Collections.Generic.Dictionary<string,string>() { ["Add"] = "+",["Subtract"] = "-",["Multiply"] = "*",["Divide"] = "/",["Mod"] = "%" })
{
var func = pair.Key;
var op = pair.Value;
#>
public static object <#=func#>(object left,object right)
{
switch(left)
{
<#
foreach(var ltype in types)
{
#> case <#=ltype#> l:
switch(right)
{
<#
foreach(var rtype in types)
{
if(ltype == "decimal" && (rtype == "float" || rtype == "double"))
continue;
if(rtype == "decimal" && (ltype == "float" || ltype == "double"))
continue;
if(ltype == "ulong" && (rtype == "sbyte" || rtype == "short" || rtype == "int" || rtype == "long"))
continue;
if(rtype == "ulong" && (ltype == "sbyte" || ltype == "short" || ltype == "int" || ltype == "long"))
continue;
#> case <#=rtype#> r:
return l <#=op#> r;
<#
}
#> default:
return <#if(op == "+")#>(right is string rs) ? l + rs : null;<#else#>null;<# #>
}
<#
}
#> default:
return null;
}
}
<#
}
}
#>
<#
{
var ltypes = new[]{ "sbyte","byte","short","ushort","int","uint","long" };
var rtypes = new[]{ "sbyte","byte","short","ushort","int" };
foreach(var pair in new System.Collections.Generic.Dictionary<string,string>() { ["Shift"] = "<<",["Unshift"] = ">>" })
{
var func = pair.Key;
var op = pair.Value;
#>
public static object <#=func#>(object left,object right)
{
switch(left)
{
<#
foreach(var ltype in ltypes)
{
#> case <#=ltype#> l:
switch(right)
{
<#
foreach(var rtype in rtypes)
{
#> case <#=rtype#> r:
return l <#=op#> r;
<#
}
#> default:
case string s:
return null;
case System.IConvertible ico when int.TryParse(ico.ToString(),out int r):
return l <#=op#> r;
}
<#
}
#> default:
return null;
}
}
<#
}
}
#>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment