c# - 从具有不同名称的成员实现接口成员
问题描述
说我有界面:
interface IThingWithId
{
int Id { get; }
}
......还有一个班级:
partial class Dog
{
public int DogId { get; set; }
}
我想扩展Dog
它以实现接口IThingWithId
,但“id”的Dog
名称不同。我曾希望这会奏效:
partial class Dog : IThingWithId {
public int Id { get; }
public Dog() {
Id = DogId;
}
}
但没有这样的运气,我得到的错误是
Dog
不实现接口成员IThingWithId.Id
。
这是可能的,还是我需要为Dog
for添加一个单独的成员Id
?
解决方案
您需要添加一个单独的成员。但是,您至少可以使用显式接口实现来“隐藏”以下用户的 ID Dog
:
class Dog : IThingWithId
{
int IThingWithId.Id => DogId;
public int DogId { get; }
}
现在你满足界面:
IThingWithId dog = new Dog();
Console.WriteLine(dog.Id); // works
Console.WriteLine(dog.DogId); // doesn't work, not part of IThingWithId
同时保持Dog
简单的公共界面:
Dog dog = new Dog();
Console.WriteLine(dog.Id); // doesn't work
Console.WriteLine(dog.DogId); // works
推荐阅读
- python - 如何在python中动态附加字典字典?
- flutter - 如果颤动中的键是数字,如何映射数据
- javascript - 如何连接 lib 目录中描述的模块?
- javascript - React:水平映射数据
- java - 我想在 Android Studio 中从我的 SQLite 数据库中删除一些东西
- rust - Rust 结构更新语法而不取得所有权
- python - 如何通过调用函数来执行 Discord 命令
- node.js - Google Sheets API 节点清除过滤器
- node.js - res.clearCookie - 删除一个 JWT 令牌
- robotframework - Robot Framework - 运行关键字 If