-1
У меня есть класс ConvertMethods, который можно динамически вызывать.C# Reflection - Casting Parameter to Type
public class ConvertMethods
{
public ConvertMethods()
{
Type type = typeof(ConvertMethods);
methodInfos = type.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
}
public Type GetParameterType(string methodName)
{
foreach (var method in methodInfos) {
if (method.Name == methodName) {
return method.GetParameters()[0].GetType();
}
}
throw new MissingMethodException("ConvertMethods", methodName);
}
public Type GetReturnType(string methodName)
{
foreach (var method in methodInfos) {
if (method.Name == methodName) {
return method.ReturnType;
}
}
throw new MissingMethodException("ConvertMethods", methodName);
}
public object InvokeMethod(string methodName, object parameter)
{
foreach (var method in methodInfos) {
if (method.Name == methodName) {
return InvokeInternal(method, parameter);
}
}
throw new MissingMethodException("ConvertMethods", methodName);
}
public static TimeSpan SecondsToTimeSpan(long seconds)
{
return TimeSpan.FromSeconds(seconds);
}
private object InvokeInternal(MethodInfo method, object parameter)
{
return method.Invoke(null, new[] { parameter });
}
private MethodInfo[] methodInfos;
}
Потенциально каждое значение, которое необходимо преобразовать, поступает из базы данных в виде строки. Я хочу динамически отображать/преобразовывать его в любой тип параметра Invoked метода. Вот что я имею:
class Program
{
static void Main(string[] args)
{
string methodName = "SecondsToTimeSpan";
string value = "10";
ConvertMethods methods = new ConvertMethods();
Type returnType = methods.GetReturnType(methodName);
Type paramType = methods.GetParameterType(methodName);
object convertedParameter = (paramType)value; // error on this line
var result = methods.InvokeMethod(methodName, convertedParameter);
Console.WriteLine(result.ToString());
}
}
Как свойство конвертировать или преобразовать String value
в любой тип ParamType содержит?
Это будет работать только для тех типов, которые имеют тип TypeConverterAttrribute, который не все делает. – GreatAndPowerfulOz
Нет, он работает для многих встроенных типов, а также –
Конечно, все те, для которых работает Convert.ChangeType. –