Comment obtenir des opérateurs définis pour un type dans .net
-
06-07-2019 - |
Question
J'essaie d'obtenir la liste des opérateurs définis pour un type spécifique afin de voir quel type d'opération peut être appliqué à ce type.
Par exemple, le type Guid prend en charge les opérations == et ! = .
Donc, si l'utilisateur veut appliquer l'opération < = pour un type de guidage, je peux gérer cette situation avant qu'une exception ne se produise.
Ou si je pouvais avoir la liste des opérateurs, je peux forcer l'utilisateur à n'utiliser que les opérations de la liste.
Les opérateurs sont vus dans l'explorateur d'objets. Il peut donc y avoir un moyen d'y accéder par réflexion, mais je ne pouvais pas le trouver.
Toute aide sera appréciée.
La solution
Obtenez les méthodes avec Type.GetMethods
, puis utilisez MethodInfo.IsSpecialName
pour découvrir des opérateurs, des conversions, etc. Voici un exemple:
using System;
using System.Reflection;
public class Foo
{
public static Foo operator +(Foo x, Foo y)
{
return new Foo();
}
public static implicit operator string(Foo x)
{
return "";
}
}
public class Example
{
public static void Main()
{
foreach (MethodInfo method in typeof(Foo).GetMethods())
{
if (method.IsSpecialName)
{
Console.WriteLine(method.Name);
}
}
}
}
Autres conseils
C # 4.0 possède une fonctionnalité d'exécution de langage dynamique, pourquoi ne pas utiliser le type dynamic
?
using Microsoft.CSharp.RuntimeBinder;
namespace ListOperatorsTest
{
class Program
{
public static void ListOperators(object inst)
{
dynamic d = inst;
try
{
var eq = d == d; // Yes, IntelliSense gives a warning here.
// Despite this code looks weird, it will do
// what it's supposed to do :-)
Console.WriteLine("Type {0} supports ==", inst.GetType().Name);
}
catch (RuntimeBinderException)
{
}
try
{
var eq = d <= d;
Console.WriteLine("Type {0} supports <=", inst.GetType().Name);
}
catch (RuntimeBinderException)
{
}
try
{
var eq = d < d;
Console.WriteLine("Type {0} supports <", inst.GetType().Name);
}
catch (RuntimeBinderException)
{
}
try
{
var add = d + d;
Console.WriteLine("Type {0} supports +", inst.GetType().Name);
}
catch (RuntimeBinderException)
{
}
try
{
var sub = d - d;
Console.WriteLine("Type {0} supports -", inst.GetType().Name);
}
catch (RuntimeBinderException)
{
}
try
{
var mul = d * d;
Console.WriteLine("Type {0} supports *", inst.GetType().Name);
}
catch (RuntimeBinderException)
{
}
try
{
try
{
var div = d / d;
}
catch (DivideByZeroException)
{
}
Console.WriteLine("Type {0} supports /", inst.GetType().Name);
}
catch (RuntimeBinderException)
{
}
}
private struct DummyStruct
{
}
static void Main(string[] args)
{
ListOperators(0);
ListOperators(0.0);
DummyStruct ds;
ListOperators(ds);
ListOperators(new Guid());
}
}
}