相关疑难解决方法(0)

在c#中使用十进制值作为属性参数?

我一直在尝试使用十进制值作为字段属性的参数但我得到编译器错误.

我发现这个博客文章链接说在.Net中使用它是不可能的,有人知道为什么他们选择这个或者我怎么能使用十进制参数?

谢谢.

c# parameters attributes decimal

78
推荐指数
2
解决办法
1万
查看次数

属性构造函数中的Lambda表达式

我创建了一个Attribute名为的类RelatedPropertyAttribute:

[AttributeUsage(AttributeTargets.Property)]
public class RelatedPropertyAttribute: Attribute
{
    public string RelatedProperty { get; private set; }

    public RelatedPropertyAttribute(string relatedProperty)
    {
        RelatedProperty = relatedProperty;
    }
}
Run Code Online (Sandbox Code Playgroud)

我用它来表示类中的相关属性.我将如何使用它的示例:

public class MyClass
{
    public int EmployeeID { get; set; }

    [RelatedProperty("EmployeeID")]
    public int EmployeeNumber { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我想使用lambda表达式,以便我可以将强类型传递给我的属性的构造函数,而不是"魔术字符串".这样我可以利用编译器类型检查.例如:

public class MyClass
{
    public int EmployeeID { get; set; }

    [RelatedProperty(x => x.EmployeeID)]
    public int EmployeeNumber { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我以为我可以使用以下内容,但编译器不允许这样做:

public RelatedPropertyAttribute<TProperty>(Expression<Func<MyClass, TProperty>> propertyExpression)
{ ... } …
Run Code Online (Sandbox Code Playgroud)

.net c# reflection attributes custom-attributes

40
推荐指数
5
解决办法
2万
查看次数

为什么十进制不是原始类型?

为什么decimal不是原始类型?

Console.WriteLine(typeof(decimal).IsPrimitive);
Run Code Online (Sandbox Code Playgroud)

输出false.

它是一种基类型,它是语言规范的一部分,但不是原语.什么原始类型代表decimal框架中的一个?一个int例如具有场m_value型的int.A double有一个m_value类型的领域double.事实并非如此decimal.它似乎是由一堆ints 代表,但我不确定.

为什么它看起来像一个原始类型,表现得像一个原始类型(除了在几种情况下)但不是原始类型?

.net c# vb.net

19
推荐指数
3
解决办法
4803
查看次数

如何接受数据的"字典"作为自定义.NET属性参数?

我最近发现,一个.NET属性只能包含基本类型,字符串,枚举,对象和这些类型的单一参数数组作为讨论在这里.

我需要IDictionary<string, string>通过.NET属性接受,但显然我不能IDictionary<string, string>因为上述原因而使用.所以,我在这里寻找可以在这些指导方针中起作用的替代方案.

// I want to do this, but can't because of the CLR limitation
[MyAttribute(Attributes = new Dictionary { { "visibility", "Condition1" }, { "myAttribute", "some-value" } })]
Run Code Online (Sandbox Code Playgroud)

我提出的两个可能的选项是在声明中使用XMLJSON(作为.NET属性上的字符串),这可以很容易地IDictionary<string, string>为我的应用程序序列化,但是这会将声明变成一个冗长的容易出错的字符串没有语法检查.

// XML
[MyAttribute(Attributes = "<items><item key='visibility' value='Condition1'/><item key='myAttribute' value='some-value'/></items>")]

// JSON
[MyAttribute(Attributes = "{ 'visibility': 'Condition1', 'myAttribute': 'some-value' }")]
Run Code Online (Sandbox Code Playgroud)

如果有的话,还有哪些其他替代方案比这更优雅/更直接?

c# xml json custom-attributes

5
推荐指数
1
解决办法
2676
查看次数