简体   繁体   中英

Generic method in C#

I am trying to make a generic method in c# where I want to return a view.

I have the following function:

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

But i get an error saying :-

Cannot convert type Android.Views.View to T

any idea how I can resolve this?

You can restrict generic parameter T being View :

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

this constraint make it easy to find errors like findViewById<int> etc.

I take it View is the same as Android.Views.View . In this case, you can write:

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

Your problem is the code is too generic. You haven't constrained T at all so any of these (and more) would be permissible:

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

And views would be an int or a string or a Form. And you can't cast a View to any of these.

So basically, you are getting the compiler error because Android.Views.View cannot be cast to every possible T.

To make this work, you need to add a constraint to T to restrict T so that it will only be Android.Views.View

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM