比较两个枚举*类型*等价? [英] Comparing two enum *types* for equivalence?

查看:117
本文介绍了比较两个枚举*类型*等价?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有两个等价的枚举。一个人住在DAL,另一个在服务契约层。它们具有相同的名称(但是在不同的命名空间中),并且应该具有相同的成员和值。

In my application, I have two equivalent enums. One lives in the DAL, the other in the service contract layer. They have the same name (but are in different namespaces), and should have the same members and values.

我想编写强制执行此功能的单元测试。到目前为止,我已经得到以下内容:

I'd like to write a unit test that enforces this. So far, I've got the following:

public static class EnumAssert
{
    public static void AreEquivalent(Type x, Type y)
    {
        // Enum.GetNames and Enum.GetValues return arrays sorted by value.
        string[] xNames = Enum.GetNames(x);
        string[] yNames = Enum.GetNames(y);

        Assert.AreEqual(xNames.Length, yNames.Length);
        for (int i = 0; i < xNames.Length; i++)
        {
            Assert.AreEqual(xNames[i], yNames[i]);
        }

        // TODO: How to validate that the values match?
    }
}

这个比较名字可以正常工作,但是怎么做我检查值是否匹配?

This works fine for comparing the names, but how do I check that the values match as well?

(我使用NUnit 2.4.6,但我认为这适用于任何单元测试框架)

(I'm using NUnit 2.4.6, but I figure this applies to any unit test framework)

推荐答案

Enum.GetValues

var xValues = Enum.GetValues(x);
var yValues = Enum.GetValues(y);

for (int i = 0; i < xValues.Length; i++)
{
    Assert.AreEqual((int)xValues.GetValue(i), (int)yValues.GetValue(i));
}

这篇关于比较两个枚举*类型*等价?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆