gpt4 book ai didi

c# - 使用泛型进行类型转换

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

我在尝试访问实现类的接口(interface)属性时遇到了问题。问题是,我在运行时只有特定的 (Cat) 类型,所以我的应用程序在尝试转换时会中断。

这是我所拥有的:

public class Animal {}
public class Cat : Animal {}

public interface IPetSitter {}
public interface IPetSitter<T> IPetSitter where T : Animal {
T Pet { get; set; }
}

public class Kid { }

public class NeighborhoodKid : Kid, IPetSitter<Animal> {
Animal Pet { get; set; }
}

// --- Implementation ---

// Kid Timmy is instantiated elsewhere
// Animal type "A" is passed in dynamically

if (Timmy is IPetSitter) {
((IPetSitter<A>)Timmy).Pet = new A();
}

如果类型不匹配,此转换将出错。我很想做这样的事情:

public interface IPetSitter {
object Pet { get; set; }
}

public interface IPetSitter<T> : IPetSitter where T : Animal {
new T Pet { get; set; }
}

// --- Implementation ---

NeighborhoodKid Timmy = new NeighborhoodKid();
((IPetSitter)Timmy).Pet = new Cat();

但这会强制任何实现 IPetSitter 的东西都具有 [object Pet] 和 [Cat Pet] 属性。

如果有任何想法,我将不胜感激。谢谢。

更新:我一开始应该说得更清楚,但有时我会创建一个 Kid类,有时是 NeighborhoodKid类(class)。这就是为什么我需要转换为 IPetSitter<T> .并非我创造的所有 child 都会坐着的宠物。这听起来令人毛骨悚然。

最佳答案

问题是你定义的

public class NeighborhoodKid : IPetSitter<Animal>
{
Animal IPetSitter<Animal>.Pet { get; set; }
}

不是

public class NeighborhoodKid : IPetSitter<Cat>
{
Cat IPetSitter<Animal>.Pet { get; set; }
}

public class NeighborhoodKid<T> : IPetSitter<T> where T : Animal
{
Cat IPetSitter<T>.Pet { get; set; }
}

关于c# - 使用泛型进行类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10503031/

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