Kotlin:如何“移植”一个类,该类扩展了使用泛型的对象和方法列表,从 c# 到 kotlin?

问题描述

我需要将一个库从 C# 移植到 Koltin,但我有一个我不知道如何“翻译”的类,有什么建议吗?

 public class MyClass: List<IMyInterface>
    {
       
        public T[] myMethod<T>() where T: class,IMyInterface
        {
            List<T> myList = new List<T>();

            foreach (IMyInterface element in this)
            {
                if (element is T)
                    myList.Add((T)element );            
            }

            return myList.ToArray();

        }
    }

解决方法

从这里直接翻译将直接从 List 派生,但随后您需要实现所有抽象方法,并且由于 C# List 等效于 Kotlin ArrayList,因此您可以简单地派生像下面这样。

class MyClass : ArrayList<IMyInterface>() {
    fun <T: IMyInterface> myMethod(): Array<T> = toTypedArray() as Array<T>
}

虽然你可以用这样的扩展方法来完成它。

fun <T: IMyInterface> List<IMyInterface>.myMethod(): Array<T> = toTypedArray() as Array<T>

请注意,您在两种情况下都会收到警告,因为您正在执行从 TIMyInterface 的未经检查的转换。

,

感谢Android Studio的建议,方法让我翻译成这样:

    inline fun <reified T : IMyInterface> myMethod() : Array<T>{
        val myList : MutableList<T> = mutableListOf()
        this.forEach { element ->
            if(element is T){
                myList.add(element)
            }
        }
        return myList.toTypedArray()
    }