go - golang是否有像'as'这样的运算符(C#)
问题描述
代码逻辑如下:
func (c *Auth) ensureCredential() (azcore, error) {
_, err = c.build(authData)
}
func (c *Auth) build(authData []byte) (*Client, error) {
return NewClient()
}
我要复制的 C# 代码
public async Task test()
{
var auth = new Auth();
var inner = await _cre(auth);
// This part code I want to copy
Client client = inner as Client
Assert some values equals Client's fileds
}
public async Task<azcore> _credential(Auth provider)
{
await provider.EnsureCredential(IsAsync, default);
return (azcore)typeof(Auth).GetField("_cre", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(provider);
}
类型Auth
和Client
实现接口azcore
。我想让Auth
as Client
测试Auth
是否等于Client
字段中的一些值。中的这些值 将根据我的代码逻辑Auth
分配给's 字段。Client
提前致谢。
解决方案
在 Go 中,接口是隐式实现的。
您可以定义一个接口,其中包含检索要比较的值所需的 getter。
type Azcore interface {
SomeValue() int // This is a getter
SomeOtherValue() string // This is a getter
}
然后你可以在 Client 类型上声明这些方法
type Client struct {
Value int
OtherValue string
ExtraValue float64
}
func (c *Client) SomeValue() int {
return c.Value
}
func (c *Client) SomeOtherValue() string {
return c.OtherValue
}
最后声明 Auth 类型的“相同”方法
type Auth struct {
Value int
SpecialValue string
}
func (a *Auth) SomeValue() int {
return a.Value
}
func (a *Auth) SomeOtherValue() string {
return a.SpecialValue
}
然后,您可以Azcore
在函数中使用类型、作为参数或作为转换的结果
func areEquals(a, b Azcore) bool {
return a.SomeValue() == b.SomeValue() && a.SomeOtherValue() == b.SomeOtherValue()
}
func (a *Auth) AsAzcore() Azcore {
return a
}
func (c *Client) AsAzcore() Azcore {
return c
}
在操场上看看
推荐阅读
- php - 给定对应于另一个数组的数组键,我如何合并它们?
- elixir - 在长生不老药中替换数组中的项目
- java - JaxRS + RestEasy - 如何创建自己的 @Context 注入字段?
- flutter - 颤动中的全屏GridView
- asp.net-core-mvc - 将 Mapster 映射代码放在 EF Core 3 和 ASP.Net MVC Core 中的什么位置?
- ruby-on-rails - 没有为演示者加载 Rails 模块
- docker - 特定的 `build` 目录未添加到 Docker 映像中
- javascript - 使用 JS 或其他方法点击后更改嵌入式 youtube 播放器的不透明度
- javascript - Tablesorter如何从表中删除选定的行
- c# - Google Drive API - 使用 API 密钥请求文件列表时出现权限错误 403 - C#