簡體   English   中英

C#中的通用方法

[英]Generic method in C#

我試圖在c#中創建一個通用方法,以便返回視圖。

我有以下功能:

public static T findViewById<T>(View parent, int id)
        {
            return (T) parent.FindViewById(id);
        }

但我得到一個錯誤說:

Cannot convert type Android.Views.View to T

知道我該如何解決嗎?

您可以通用參數T 限制View

public static T findViewById<T>(View parent, int id)
  where T: View
{
  return (T) parent.FindViewById(id);
}

此約束使查找錯誤(如findViewById<int>等)變得容易。

我認為ViewAndroid.Views.View相同。 在這種情況下,您可以編寫:

public static T findViewById<T>(T parent, int id)
        {
            return parent.FindViewById(id);
        } where T : View

您的問題是代碼太通用。 您根本沒有約束T,因此這些(或更多)中的任何一個都是允許的:

var views = findViewById<int>(parent, id);
var views = findViewById<String>(parent, id);
var views = findViewById<Form>(parent, id);

並且views將是一個int或一個字符串或一個Form。 而且您無法對其中任何一個View進行投射。

因此,基本上,您會遇到編譯器錯誤,因為Android.Views.View不能Android.Views.View為所有可能的T。

為此,您需要在T上添加一個約束以限制T,以便它只能是Android.Views.View

public static T findViewById<T>(View parent, int id) 
    where T : Android.Views.Views
{
    return (T) parent.FindViewById(id);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM