gpt4 book ai didi

c# - 关于 c# 泛型类型的维度信息有什么好处

转载 作者:行者123 更新时间:2023-12-02 22:25:06 27 4
gpt4 key购买 nike

所以这已经在 S.O. 上讨论过了。然而,在此之前,我认为我从未真正看到过为什么会发生这种情况的解释,我似乎也无法理解这对试图在他们的代码中使用反射的普通开发人员有何用处。

所以检查这段代码。

var fields = typeof(Person).GetFields(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Instance);

如果我有一个 List<int>在我的 Person对象然后我将取回一个字段,该字段的反射“名称”设置为 List`1 ,或者如果我有字典,它将是 Dictionary`2 .从表面上看,这似乎很难使用,我不能说以下内容

foreach (var fieldInfo in fields.Where(fieldInfo => fieldInfo.FieldType == typeof(List<int>)))
{
//Do something.
}

出现这种情况的原因是因为我在我目前正在从事的项目中发现了以下内容。

    //Initialize collections
FieldInfo[] properties = type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (FieldInfo f in properties)
{
if (f.FieldType.Name == "IList`1" && f.GetValue(obj) == null)
{
object value = Container.Resolve(f.FieldType);
f.SetValue(obj, value);

}
}

然后在统一的配置中我看到了这种幸福

<alias alias="IList`1" type="System.Collections.Generic.IList`1, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>

我真的不知道我知道这不好吗?是吗?它当然有效,但即使这没问题(这会导致我的可疑代码 dar 消失),我最初的问题仍然存在。关于泛型的维度信息对我们程序员有什么好处?

最佳答案

它肯定不是用来帮助程序员的。它在那里是因为 CLI 需要它。进一步的理由是,它确保具有相同标识符名称但不同数量的类型参数的泛型类型具有唯一的类型名称。 ECMA 335 规范中的一些措辞:

CLS Rule 43: The name of a generic type shall encode the number of type parameters declared on the non-nested type, or newly introduced to the type if nested, according to the rules defined above. [Note: CLS (consumer): Need not consume types that violate this rule. CLS (extender): Same as consumers. Extenders choosing to support definition of generic types shall follow this rule for externally visible types. CLS (framework): Shall not expose types that violate this rule. end note]

在第 II.9 节中做了一些说明:

A generic type consists of a name followed by a <…>-delimited list of generic parameters, as in C<T>. Two or more generic types shall not be defined with the same name, but different numbers of generic parameters, in the same scope. However, to allow such overloading on generic arity at the source language level, CLS Rule 43 is defined to map generic type names to unique CIL names. That Rule states that the CLS-compliant name of a type C having one or more generic parameters, shall have a suffix of the form `n, where n is a decimal integer constant (without leading zeros) representing the number of generic parameters that C has. For example: the types C, C<T>, and C<K,V> have CLS-compliant names of C, C1<T>, andC2<K,V>, respectively. [Note: The names of all standard library types are CLS-compliant; e.g., System.Collections.Generic.IEnumerable`1. end note]

抱歉,没有完全正确,发布答案时反引号很棘手。请查看 ECMA 文档以确保准确性。

关于c# - 关于 c# 泛型类型的维度信息有什么好处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13087826/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com