关于C#中泛型类型参数约束(where T : class)
2021-03-26 17:28
阅读:826
.NET支持的类型参数约束有以下五种:
where T : struct | T必须是一个结构类型
where T : class | T必须是一个Class类型
where T : new() | T必须要有一个无参构造函数
where T : NameOfBaseClass | T必须继承名为NameOfBaseClass的类
where T : NameOfInterface | T必须实现名为NameOfInterface的接口
如下在WPF中获取当前窗体(或者用户控件)的父窗体,限定泛型必须为Class:

private void btnCancel_Click(object sender, RoutedEventArgs e)
{
Window hostWindow = GetParent(sender as Button);
if (hostWindow != null)
{
hostWindow.Close();
}
}
public static T GetParent(UIElement uiElement) where T : class
{
T result;
var dp = LogicalTreeHelper.GetParent(uiElement);
result = dp as T;
while (result == null)
{
dp = LogicalTreeHelper.GetParent(dp);
result = dp as T;
if (dp == null) return null;
}
return result;
}

上一篇:Windos下PIP配置豆瓣源
下一篇:window界面控制
文章来自:搜素材网的编程语言模块,转载请注明文章出处。
文章标题:关于C#中泛型类型参数约束(where T : class)
文章链接:http://soscw.com/essay/68220.html
文章标题:关于C#中泛型类型参数约束(where T : class)
文章链接:http://soscw.com/essay/68220.html
评论
亲,登录后才可以留言!