惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

GbyAI
GbyAI
O
OpenAI News
Jina AI
Jina AI
腾讯CDC
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
MongoDB | Blog
MongoDB | Blog
J
Java Code Geeks
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Tailwind CSS Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
WordPress大学
WordPress大学
F
Full Disclosure
Microsoft Azure Blog
Microsoft Azure Blog
I
InfoQ
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
www.infosecurity-magazine.com
www.infosecurity-magazine.com
SecWiki News
SecWiki News
F
Fortinet All Blogs
C
Check Point Blog
H
Hacker News: Front Page
H
Help Net Security
G
Google Developers Blog
The Cloudflare Blog
Google Online Security Blog
Google Online Security Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
A
About on SuperTechFans
S
Secure Thoughts
U
Unit 42
L
LINUX DO - 最新话题
博客园 - 【当耐特】
量子位
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 叶小钗
TaoSecurity Blog
TaoSecurity Blog
Recorded Future
Recorded Future
Apple Machine Learning Research
Apple Machine Learning Research
AI
AI
aimingoo的专栏
aimingoo的专栏
Security Archives - TechRepublic
Security Archives - TechRepublic
H
Heimdal Security Blog
Y
Y Combinator Blog
月光博客
月光博客
Hacker News: Ask HN
Hacker News: Ask HN
D
DataBreaches.Net
Webroot Blog
Webroot Blog
T
Troy Hunt's Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Schneier on Security
Schneier on Security
Cisco Talos Blog
Cisco Talos Blog
Last Week in AI
Last Week in AI

博客园 - Jacky

Four early-PayPal entrepreneurial culture norms →How Facebook Ships Code An Introduction to C# Generics http://arstechnica.com Scaling memcached at Facebook httpserver,下面是rfc相关信息: 目前互联网上公布出来的正文提取算法,大家可以综合比较下,一起来测试下哪个更好用。 词网--北京词网科技有限公司 http://demo.cikuu.com/cgi-bin/cgi-contex 猎兔网页正文提取 http://www.lie In a nutshell: A Basic Comparison of Heap-Sort and Quick-Sort Algorithms C#中string.Format的格式参数问题 - Jacky - 博客园 mit 2 mit Process Monitor监测记录表明,QQ不仅会自动访问许多与聊天无关的程序和文档,例如“我的文档”等敏感位置,测试当天的上网记录也没能幸免。随后,QQ还会产生大量网络通讯,很可能是将数据上传到腾讯服务器。短短10分钟内,它访问的无关 搜索引擎高级搜索技巧 harvard 十年了,馅饼西施的馅饼还是那么正 她讲课的缺点是讲起课来波澜不惊,按着课本步步来.容易看不下去,不过确实能进一步学到一些知识。喜欢的顶起来 9。指针参数的内存传递。 - Jacky - 博客园 模块间调用重载new和delete问题 转 内存泄露检测,重载new
Constraints on Type Parameters (C# Programming Guide)
Jacky · 2011-01-20 · via 博客园 - Jacky

When you define a generic class, you can apply restrictions to the kinds of types that client code can use for type arguments when it instantiates your class. If client code attempts to instantiate your class with a type that is not allowed by a constraint, the result is a compile-time error. These restrictions are called constraints. Constraints are specified using the where contextual keyword. The following table lists the six types of constraints:

Constraint Description

where T: struct

The type argument must be a value type. Any value type except Nullable can be specified. See Using Nullable Types (C# Programming Guide) for more information.

where T : class

The type argument must be a reference type, including any class, interface, delegate, or array type. (See note below.)

where T : new()

The type argument must have a public parameterless constructor. When used in conjunction with other constraints, the new() constraint must be specified last.

where T : <base class name>

The type argument must be or derive from the specified base class.

where T : <interface name>

The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic.

where T : U

The type argument supplied for T must be or derive from the argument supplied for U. This is called a naked type constraint.

NoteNote

In the .NET Framework 2.0, recursively defined generic type constraints may in some cases result in a BadImageFormatException at runtime. The workaround is to remove the where T : class constraint on the enclosing type. For more information, see Feedback ID #93389 on the Microsoft Connect web site and Microsoft Knowledge Base article 940164.

If you want to examine an item in a generic list to determine whether it is valid or to compare it to some other item, the compiler must have some guarantee that the operator or method it needs to call will be supported by any type argument that might be specified by client code. This guarantee is obtained by applying one or more constraints to your generic class definition. For example, the base class constraint tells the compiler that only objects of this type or derived from this type will be used as type arguments. Once the compiler has this guarantee, it can allow methods of that type to be called within the generic class. Constraints are applied using the contextual keyword where. The following code example demonstrates the functionality we can add to the GenericList<T> class (in Introduction to Generics (C# Programming Guide)) by applying a base class constraint.

public class Employee
{
    private string name;
    private int id;

    public Employee(string s, int i)
    {
        name = s;
        id = i;
    }

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    public int ID
    {
        get { return id; }
        set { id = value; }
    }
}

public class GenericList<T> where T : Employee
{
    private class Node
    {
        private Node next;
        private T data;

        public Node(T t)
        {
            next = null;
            data = t;
        }

        public Node Next
        {
            get { return next; }
            set { next = value; }
        }

        public T Data
        {
            get { return data; }
            set { data = value; }
        }
    }

    private Node head;

    public GenericList() //constructor
    {
        head = null;
    }

    public void AddHead(T t)
    {
        Node n = new Node(t);
        n.Next = head;
        head = n;
    }

    public IEnumerator<T> GetEnumerator()
    {
        Node current = head;

        while (current != null)
        {
            yield return current.Data;
            current = current.Next;
        }
    }

    public T FindFirstOccurrence(string s)
    {
        Node current = head;
        T t = null;

        while (current != null)
        {
            //The constraint enables access to the Name property.
            if (current.Data.Name == s)
            {
                t = current.Data;
                break;
            }
            else
            {
                current = current.Next;
            }
        }
        return t;
    }
}

The constraint enables the generic class to use the Employee.Name property since all items of type T are guaranteed to be either an Employee object or an object that inherits from Employee.

Multiple constraints can be applied to the same type parameter, and the constraints themselves can be generic types, as follows:

class EmployeeList<T> where T : Employee, IEmployee, System.IComparable<T>, new()
{
    // ...
}

By constraining the type parameter, you increase the number of allowable operations and method calls to those supported by the constraining type and all types in its inheritance hierarchy. Therefore, when designing generic classes or methods, if you will be performing any operation on the generic members beyond simple assignment or calling any methods not supported by System.Object, you will need to apply constraints to the type parameter.

When applying the where T : class constraint, it is recommended that you do not use the == and != operators on the type parameter because these operators will test for reference identity only, not for value equality. This is the case even if these operators are overloaded in a type used as an argument. The following code illustrates this point; the output is false even though the String class overloads the == operator.

public static void OpTest<T>(T s, T t) where T : class
{
    System.Console.WriteLine(s == t);
}
static void Main()
{
    string s1 = "foo";
    System.Text.StringBuilder sb = new System.Text.StringBuilder("foo");
    string s2 = sb.ToString();
    OpTest<string>(s1, s2);
}

The reason for this behavior is that, at compile time, the compiler only knows that T is a reference type, and therefore must use the default operators that are valid for all reference types. If you need to test for value equality, the recommended way is to also apply the where T : IComparable<T> constraint and implement that interface in any class that will be used to construct the generic class.

Unbounded Type Parameters

Type parameters that have no constraints, such as T in public class SampleClass<T>{}, are called unbounded type parameters. Unbounded type parameters have the following rules:

  • The != and == operators cannot be used because there is no guarantee that the concrete type argument will support these operators.

  • They can be converted to and from System.Object or explicitly converted to any interface type.

  • You can compare to null. If an unbounded parameter is compared to null, the comparison will always return false if the type argument is a value type.

When a generic type parameter is used as a constraint, it is called a naked type constraint. Naked type constraints are useful when a member function with its own type parameter needs to constrain that parameter to the type parameter of the containing type, as shown in the following example:

class List<T>
{
    void Add<U>(List<U> items) where U : T {/*...*/}
}

In the previous example, T is a naked type constraint in the context of the Add method, and an unbounded type parameter in the context of the List class.

Naked type constraints can also be used in generic class definitions. Note that the naked type constraint must also have been declared within the angle brackets along with any other type parameters:

//naked type constraint
public class SampleClass<T, U, V> where T : V { }

The usefulness of naked type constraints with generic classes is very limited because the compiler can assume nothing about a naked type constraint except that it derives from System.Object. Use naked type constraints on generic classes in scenarios in which you wish to enforce an inheritance relationship between two type parameters.