我有以下 C# 模型(理论示例):
public class Filename
{
public string Name { get; set; }
public string Description { get; set; }
}
namespace Protobuf // Auto-generated
{
public class Filename
{
public string Name { get; set; }
public string Description { get; set; }
}
}
我希望能够使用简单的方法将“文件名”类型转换为“Protobuf.Filename”类型。
现在我也知道 Rust 了。在这种情况下,我会在 Rust 中创建一个特征并在“文件名”类型上实现它,如下所示:
trait ToProto<TProto> {
fn to_proto(&self) -> TProto;
}
impl ToProto<protobuf::Filename> for Filename {
fn to_proto(&self) -> protobuf::Filename {
protobuf::Filename {
format_string: self.format_string,
description: self.description,
}
}
}
据我所知,在带有协议和扩展的 Swift 中,类似的东西是可能的。
我在考虑在 C# 中使用接口和扩展方法,但这些似乎并不能很好地相互配合。 例如,这不是有效的 C#:
public interface IProtoConvertible<T, TProto>
{
public TProto ToProto(this T value);
}
我可以完全省略接口并只使用扩展方法,但这会导致大量重复代码尖叫“这可以更通用!”。
我是不是忽略了什么?这在 C# 中可能吗?
提前致谢。
也许你需要这样的东西:
public interface IProtoConvertible<T, TProto> where T : class
where TProto : class
{
public TProto ToProto<T>(T value)
{
// implementation here
// return (TProto)new object();
}
}
从 C# 8.0 开始,可以在接口方法中编写实现。