开发者

C# where keyword [duplicate]

开发者 https://www.devze.com 2022-12-29 01:02 出处:网络
This question already has answers here: What does the keyword "where" in a class declaration do?
This question already has answers here: What does the keyword "where" in a class declaration do? (7 answers) Closed 9 years ago.

In the following piece of code (C# 2.0):

public abstract class ObjectMapperBase< T > where T : new()
{
    internal abstract bool UpdateObject( T plainObjectOrginal,
                                         T plainObjectNew,
                                         WebMethod fwm,
                                         IDbTransaction transaction );
}

Inheritor example:

public abstract class OracleObjectMapperBase< T > : ObjectMapperBase< T > where T : new()
{
    internal override bool UpdateObject( T plainObjectOrginal,
                                         T plainObjectNew,
                                         WebMethod fwm,
                                         IDbTransaction transaction )
    {
        // Fancy Reflection code开发者_Go百科.
    }
}

What does the where keyword do?


it is a constraint for generics

MSDN

so the new() constraint says it must have a public parameterless constructor


It specifies a constraint on the generic type parameter T.

The new() constraint specifies that T must have a public default constructor.

You can also stipulate that the type must be a class (or conversely, a struct), that it must implement a given interface, or that it must derive from a particular class.


The where clause is used to specify constraints on the types that can be used as arguments for a type parameter defined in a generic declaration. For example, you can declare a generic class, MyGenericClass, such that the type parameter T implements the IComparable interface:

public class MyGenericClass<T> where T:IComparable { }

In this particular case it says that T must implement a default constructor.


This is a generic type constraint. It means that the generic type T must implement a zero parameter constructor.


The Where keyword is basically a constraint on the objects the class can work on/with.

taken from MSDN "The new() Constraint lets the compiler know that any type argument supplied must have an accessible parameterless constructor"

http://msdn.microsoft.com/en-us/library/6b0scde8(VS.80).aspx


It means the T has to have a public default constructor.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号