微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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()
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。