首页 > 解决方案 > 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);
}

类型AuthClient实现接口azcore。我想让Auth as Client测试Auth是否等于Client字段中的一些值。中的这些值 将根据我的代码逻辑Auth分配给's 字段。Client

提前致谢。

标签: gotesting

解决方案


在 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
}

在操场上看看


推荐阅读