小编mer*_*erp的帖子

C#4.0中的通用列表

我正在尝试使用C#和.NET 4.0创建通用列表

List<var> varlist = new List<var>(); 此代码产生错误"上下文关键字'var'可能只出现在局部变量声明中"

原因是因为我想做这样的事情:

List<var> varList = new List<var>(); // Declare the generic list
List<Object1> listObj1;              // List of Object1
List<Object2> listObj2;              // List of Object2

varList = listObj1;                  // Assign the var list to list of Object1

varList = listObj2;                  // Re-assign the var list to the list of Object2
Run Code Online (Sandbox Code Playgroud)

有没有办法在C#.NET 4.0中执行此操作?

.net c# generics

3
推荐指数
1
解决办法
234
查看次数

按类型动态访问属性

我正在尝试访问与传递给泛型的相同类型的属性.

看看代码:

class CustomClass
{
    CustomProperty property {get; set;}
}

class CustomProperty
{
}

Main
{
        // Create a new instance of my custom class
        CustomClass myClass = new CustomClass();

        // Create a new instance of another class that is the same type as myClass.property
        CustomProperty myProp = new CustomProperty();

        // Call the generic method 
        DynamicallyAccessPropertyOnObject<CustomProperty>(myProp, myClass);
}


private void DynamicallyAccessPropertyOnObject<T>(this T propertyToAccess, CustomClass class)
{
    // I want to access the property (In class) that is the same type …
Run Code Online (Sandbox Code Playgroud)

.net c# generics

0
推荐指数
1
解决办法
68
查看次数

标签 统计

.net ×2

c# ×2

generics ×2