1. 程式人生 > >關於C#中泛型類型參數約束(where T : class)

關於C#中泛型類型參數約束(where T : class)

name ica title logic .get ted inter host ase

.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<Window>(sender as Button);
            if (hostWindow != null)
            {
                hostWindow.Close();
            }
        }

        public static T GetParent<T>(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;
        }
技術分享圖片

關於C#中泛型類型參數約束(where T : class)