使用枚举或标志作为用户控件 属性

Using Enum or flag as user control property

我有一个 Web 用户控件,其类型 属性 是一个标志:

在服务器端代码中,我可以像这样分配它:

Type = GraphTypes.Comment | GraphTypes.Like;

但是当像这样添加用户控件时:

<uc:Graph Type="Comment|Like" runat="server" />

我遇到一个错误:

Cannot create an object of type 'GraphTypes' from its string representation 'Comment|Like' for the 'Type' property.

如何在我的代码中分配 Comment|Like 的值?

假设您的 GraphTypes Enum 看起来像

[Flags]
enum GraphTypes
{
    Comment = 1,
    Like = 2,
    Foo = 4,
    Bar = 8
}

你只需要更换

Type="Comment|Like"

Type="Comment,Like"

等于GraphTypes Type = GraphTypes.Comment | GraphTypes.Like;GraphTypes Type = (GraphTypes)3;