gpt4 book ai didi

c# - 将非泛型转换为泛型

转载 作者:行者123 更新时间:2023-11-30 12:18:15 24 4
gpt4 key购买 nike

我有这门课:

class Foo { 
public string Name { get; set; }
}

还有这个类

class Foo<T> : Foo {
public T Data { get; set; }
}

这是我想做的:

public Foo<T> GetSome() {
Foo foo = GetFoo();

Foo<T> foot = (Foo<T>)foo;
foot.Data = GetData<T>();
return foot;
}

将 Foo 转换为 Foo 的最简单方法是什么?我不能直接转换 InvalidCastException),如果不需要的话,我不想手动复制每个属性(在我的实际用例中,有多个属性)。用户定义的类型转换是可行的方法吗?

最佳答案

您可以在 Foo<T> 中创建从 Foo 的显式转换.

class Program
{
static void Main()
{
Foo foo = new Foo();
foo.Name = "Blah";
Foo<int> newfoo = (Foo<int>)foo;
Console.WriteLine(newfoo.Name);
Console.Read();
}
}

class Foo
{
public string Name { get; set; }
public object Data { get; set; }
}

class Foo<T>
{
public string Name { get; set; }
public T Data { get; set; }
public static explicit operator Foo<T>(Foo foo)
{
Foo<T> newfoo = new Foo<T>();
newfoo.Name = foo.Name;
return newfoo;
}
}

编辑: 这只在没有继承的情况下有效。看来您无法执行从基类到派生类的用户定义转换。请在此处查看 Mads Torgersen 的评论 http://social.msdn.microsoft.com/forums/en-US/csharplanguage/thread/14cf27cf-b185-43d6-90db-734d2ca3c8d4/ :

We have taken the liberty of predefining conversions (casts) between base classes and derived classes, and to make the semantics of the language predictable we don't allow you to mess with it.

看起来您可能无法定义一个将 Foo 转换为 Foo<T> 的方法。 .那,或者放弃继承。这两种解决方案听起来都不是特别理想。

关于c# - 将非泛型转换为泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2535835/

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