c# - 如何编写一个方法来接受一个类型作为参数,并在方法体内使用它来将另一个变量转换为该传递的类型?

标签 c#

我想要的是有一个接受类型作为参数的方法,并在 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/

相关文章:

c# - UWP LogicalTreeViewHelper

c# - Autofac 模块应该注册自己的依赖模块吗?

c# - 列序列和 Entity Framework

c# - 如何使用连接从 linq 结果中获取所有列

c# - List Occurence 明智地阅读 c#

c# - 使用 PrincipalContext.ValidateCredentials 对本地计算机进行身份验证时出错?

c# - 如何在 Monotouch 中绑定(bind)扩展方法?

c# - 定义字典之间的区别

c# - Java 中 @Deprecated 的 .NET 等价物是什么?

c# Panel with auto scroll - 在控件焦点上重置滚动条位置