gpt4 book ai didi

c# - 如何使用传递给 C# 中当前方法的实现来实例化接口(interface)对象?

转载 作者:太空宇宙 更新时间:2023-11-03 21:13:58 25 4
gpt4 key购买 nike

给定一个简单的界面

public interface IIdTracker
{
int Id { get; }
}

我有两个实现它的类

public class human : IIdTracker
{
public int Id { return 0; }
}

public class robot : IIdTracker
{
public int Id { return 1; }
}

如何在不知道谁或什么正在实现 IIdTracker 的情况下实例化作为 IIdTracker 传递的任何类?

public void TrackId(IIdTracker idt)
{
// this is the code I am not sure of
var being = new idt.GetType();
}

最佳答案

经过一番研究,我发现

var being = Activator.CreateInstance(idt.GetType()) as IIdTracker;

作为解决方案。

关于c# - 如何使用传递给 C# 中当前方法的实现来实例化接口(interface)对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35711863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com