Yönetilmeyen tür kısıtlamasıUnmanaged type constraint
ÖzetSummary
Yönetilmeyen kısıtlama özelliği, C# dil belirtiminde "yönetilmeyen türler" olarak bilinen türlerin sınıfına dil zorlaması verecektir. Bu, başvuru türü olmayan ve herhangi bir iç içe geçme düzeyinde başvuru türü alanları içermeyen bir tür olarak 18,2 bölümünde tanımlanmıştır.The unmanaged constraint feature will give language enforcement to the class of types known as "unmanaged types" in the C# language spec. This is defined in section 18.2 as a type which is not a reference type and doesn't contain reference type fields at any level of nesting.
MotivasyonMotivation
Birincil mosyon, C# ' ta düşük düzey birlikte çalışma kodu yazmayı kolaylaştırmaktır.The primary motivation is to make it easier to author low level interop code in C#. Yönetilmeyen türler, birlikte çalışma kodu için temel yapı taşlarından biridir, ancak genel türlerde desteğin olmaması, tüm yönetilmeyen türler arasında yeniden kullanılabilir yordamlar oluşturmayı olanaksız hale getirir.Unmanaged types are one of the core building blocks for interop code, yet the lack of support in generics makes it impossible to create re-usable routines across all unmanaged types. Bunun yerine, geliştiriciler kitaplığındaki her yönetilmeyen tür için aynı Boiler levha kodunu yazmak üzere zorlanır:Instead developers are forced to author the same boiler plate code for every unmanaged type in their library:
int Hash(Point point) { ... }
int Hash(TimeSpan timeSpan) { ... }
Bu tür bir senaryoyu etkinleştirmek için dil yeni bir kısıtlama tanıtıyor: yönetilmeyen:To enable this type of scenario the language will be introducing a new constraint: unmanaged:
void Hash<T>(T value) where T : unmanaged
{
...
}
Bu kısıtlama yalnızca C# dil belirtiminde yönetilmeyen tür tanımına sığan türlerle karşılanabilecek. Bir başka yol da bir işaretçi olarak kullanılabilecek bir tür yönetilmeyen kısıtlamayı karşılar.This constraint can only be met by types which fit into the unmanaged type definition in the C# language spec. Another way of looking at it is that a type satisfies the unmanaged constraint if it can also be used as a pointer.
Hash(new Point()); // Okay
Hash(42); // Okay
Hash("hello") // Error: Type string does not satisfy the unmanaged constraint
Yönetilmeyen kısıtlama içeren tür parametreleri, yönetilmeyen türler için kullanılabilen tüm özellikleri kullanabilir: işaretçiler, sabit, vb...Type parameters with the unmanaged constraint can use all the features available to unmanaged types: pointers, fixed, etc ...
void Hash<T>(T value) where T : unmanaged
{
// Okay
fixed (T* p = &value)
{
...
}
}
Bu kısıtlama, yapılandırılmış veriler ve bayt akışları arasında verimli dönüştürmeler olmasını da mümkün kılar.This constraint will also make it possible to have efficient conversions between structured data and streams of bytes. Bu, ağ yığınları ve serileştirme katmanlarında ortak olan bir işlemdir:This is an operation that is common in networking stacks and serialization layers:
Span<byte> Convert<T>(ref T value) where T : unmanaged
{
...
}
Bu tür yordamlar, derleme zamanında provably güvende olduklarından ve serbest bırakıldığı için avantajlıdır.Such routines are advantageous because they are provably safe at compile time and allocation free. Birlikte çalışma yazarları bugün bunu yapamayabilir (performans açısından kritik olan bir katmanda olmasına rağmen).Interop authors today can not do this (even though it's at a layer where perf is critical). Bunun yerine, değerlerin doğru şekilde yönetilmeyen olduğunu doğrulamak için pahalı çalışma zamanı denetimleri olan yordamları ayırmaya güvenmeleri gerekir.Instead they need to rely on allocating routines that have expensive runtime checks to verify values are correctly unmanaged.
Ayrıntılı tasarımDetailed design
Dilde adlı yeni bir kısıtlama tanıtılacaktır unmanaged .The language will introduce a new constraint named unmanaged. Bu kısıtlamayı karşılamak için, bir tür yapı olmalıdır ve türün tüm alanları aşağıdaki kategorilerden birine denk gelmelidir:In order to satisfy this constraint a type must be a struct and all the fields of the type must fall into one of the following categories:
- ,,,,,,,
sbytebyteshortushortintuintlongulong,char,float,,doubledecimal,boolIntPtrVeyaUIntPtrtüründe olmalıdır.Have the typesbyte,byte,short,ushort,int,uint,long,ulong,char,float,double,decimal,bool,IntPtrorUIntPtr. - Herhangi bir
enumtür olun.Be anyenumtype. - Bir işaretçi türü olmalıdır.Be a pointer type.
- Kısıtlamayı karşılayan Kullanıcı tanımlı bir yapı olmalıdır
unmanaged.Be a user defined struct that satisfies theunmanagedconstraint.
Derleyici tarafından oluşturulan örnek alanları, örneğin otomatik uygulanan özellikler, bu kısıtlamaları da karşılamalıdır.Compiler generated instance fields, such as those backing auto-implemented properties, must also meet these constraints.
Örnek:For example:
// Unmanaged type
struct Point
{
int X;
int Y {get; set;}
}
// Not an unmanaged type
struct Student
{
string FirstName;
string LastName;
}
unmanagedKısıtlama struct , veya ile birleştirilemez class new() .The unmanaged constraint cannot be combined with struct, class or new(). Bu kısıtlama, unmanaged struct diğer kısıtlamaların anlamlı olmaması açısından önemli olan olgusunun türetiliyor.This restriction derives from the fact that unmanaged implies struct hence the other constraints do not make sense.
unmanagedKısıtlama, yalnızca dil tarafından CLR tarafından zorlanmaz.The unmanaged constraint is not enforced by CLR, only by the language. Diğer dillerin yanlış kullanımını engellemek için, bu kısıtlamaya sahip Yöntemler bir mod-REQ tarafından korunur. Bu, diğer dillerin yönetilmeyen türler olmayan tür bağımsız değişkenlerini kullanmasını engeller.To prevent mis-use by other languages, methods which have this constraint will be protected by a mod-req. This will prevent other languages from using type arguments which are not unmanaged types.
unmanagedKısıtlamadaki belirteç bir anahtar sözcük ya da bağlamsal anahtar sözcük değil.The token unmanaged in the constraint is not a keyword, nor a contextual keyword. Bunun yerine, var söz konusu konumda değerlendirilmek ve şöyle olacaktır:Instead it is like var in that it is evaluated at that location and will either:
- Kullanıcı tanımlı veya başvurulan türe bağla
unmanaged: Bu, başka bir adlandırılmış tür kısıtlaması işlendiği gibi değerlendirilir.Bind to user defined or referenced type namedunmanaged: This will be treated just as any other named type constraint is treated. - Hiçbir tür için bağlama: Bu, kısıtlama olarak yorumlanacaktır
unmanaged.Bind to no type: This will be interpreted as theunmanagedconstraint.
Adında bir tür varsa unmanaged ve geçerli bağlamda nitelendirme olmadan kullanılabiliyorsa, kısıtlamayı kullanmanın bir yolu olmayacaktır unmanaged .In the case there is a type named unmanaged and it is available without qualification in the current context, then there will be no way to use the unmanaged constraint. Bu, özelliği çevreleyen kuralları var ve aynı ada sahip kullanıcı tanımlı türleri paraleller.This parallels the rules surrounding the feature var and user defined types of the same name.
BulunmaktadırDrawbacks
Bu özelliğin birincil dezavantajı, az sayıda geliştirici sunmesidir: genellikle düşük düzey kitaplık yazarları veya çerçeveleri.The primary drawback of this feature is that it serves a small number of developers: typically low level library authors or frameworks. Bu nedenle, az sayıda geliştirici için değerli bir dil süresi harcadığından.Hence it's spending precious language time for a small number of developers.
Bu çerçeveler, genellikle burada .NET uygulamalarının çoğunluğunun temelini oluşturur.Yet these frameworks are often the basis for the majority of .NET applications out there. Bu nedenle, bu düzeyde WINS performansı/doğruluğu, .NET ekosistemi üzerinde Ripple etkiye sahip olabilir.Hence performance / correctness wins at this level can have a ripple effect on the .NET ecosystem. Bu, özelliği sınırlı kitlelerle hatta göz önünde bulundurmayı sağlar.This makes the feature worth considering even with the limited audience.
AlternatiflerAlternatives
Göz önünde bulundurulması gereken birkaç seçenek vardır:There are a couple of alternatives to consider:
- Durum Quo: Özellik kendi birleşmesine göre hizalı değildir ve geliştiriciler örtük kabul etme davranışını kullanmaya devam eder.The status quo: The feature is not justified on its own merits and developers continue to use the implicit opt in behavior.
SorularQuestions
Meta veri gösterimiMetadata Representation
F # dili imza dosyasındaki kısıtlamayı kodluyor, bu, C# gösterimini yeniden kullanamayacağı anlamına gelir.The F# language encodes the constraint in the signature file which means C# cannot re-use their representation. Bu kısıtlama için yeni bir özniteliğin seçilmesi gerekir.A new attribute will need to be chosen for this constraint. Ayrıca, bu kısıtlamayı içeren bir yöntemin bir mod-REQ tarafından korunması gerekir.Additionally a method which has this constraint must be protected by a mod-req.
Blittable vs. yönetilmeyenBlittable vs. Unmanaged
F # dilinin yönetilmeyen anahtar sözcüğünü kullanan çok benzer bir özelliği vardır.The F# language has a very similar feature which uses the keyword unmanaged. Blittable adı Midori ' deki kullanım öğesinden gelir.The blittable name comes from the use in Midori. Burada önceliğe bakmak ve bunun yerine yönetilmeyen ' i kullanmak isteyebilir.May want to look to precedence here and use unmanaged instead.
Çözüm Yönetilmeyen bu dilin kullanımına kararResolution The language decide to use unmanaged
'NınVerifier
Genel tür parametrelerine işaretçiler kullanımını anlamak için doğrulayıcı/çalışma zamanının güncellenmesi gerekiyor mu?Does the verifier / runtime need to be updated to understand the use of pointers to generic type parameters? Ya da yalnızca değişiklik olmayan şekilde çalışabilir mi?Or can it simply work as is without changes?
Çözüm Değişiklik gerekmiyor.Resolution No changes needed. Tüm işaretçi türleri doğrulanamaz.All pointer types are simply unverifiable.
Tasarım toplantılarıDesign meetings
yokn/a