我想要的是有一个接受类型作为参数的方法,并在 C# 的方法中将变量转换为该类型
例如,我想将一个 UI 元素传递给此辅助方法并提取其 DataContext 的(在运行时动态绑定(bind)的)描述。我想以更通用的方式使用此方法,以便我也可以传入 DataContext 的类型。
private String GetDescription(FrameworkElement element, Type type) {
return (element.DataContext as type).Description;
//or
//return ((type)element.DataContext).Description;
}
两种方式都以编译时错误结束。
我也尝试过使用泛型,但没有成功,因为我可能没有正确理解。
如果有人能以简单的方式解释如何做到这一点,那就太好了。
最佳答案
编写一个接口(interface)
并为您的类实现它:
public interface IDescribable
{
string Description{get;}
}
在你想要的类上实现这个对象:
public class MyClass:IDescribable
{
// other members
public string Description{get; set;}
}
然后你甚至可以写一个扩展方法来提取字符串:
public static string GetDescription(this FrameworkElement element)
{
var contextData= element.DataContext as IDescribable;
return contextData!=null
? contextData.Description
:"";
}
或者如果你不想实现 interface
使用反射:
private string GetDescription(FrameworkElement element)
{
var decProp= element.DataContext.GetType().GetProperty("Description");
return decProp!=null
?decProp.GetValue(element.DataContext)
:"";
}
关于c# - 如何编写一个方法来接受一个类型作为参数,并在方法体内使用它来将另一个变量转换为该传递的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31784343/