本文整理汇总了C#中System.Compiler.Class类的典型用法代码示例。如果您正苦于以下问题:C# Class类的具体用法?C# Class怎么用?C# Class使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Class类属于System.Compiler命名空间,在下文中一共展示了Class类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: CollectOldExpressions
public CollectOldExpressions(Module module, Method method, ContractNodes contractNodes, Dictionary<TypeNode, Local> closureLocals,
int localCounterStart, Class initialClosureClass)
: this(module, method, contractNodes, closureLocals, localCounterStart)
{
this.topLevelClosureClass = initialClosureClass;
this.currentClosureClass = initialClosureClass;
}
开发者ID:asvishnyakov,项目名称:CodeContracts,代码行数:7,代码来源:CollectOldExpressions.cs
示例2: ScrubContractClass
public ScrubContractClass(ExtractorVisitor parent, Class contractClass, TypeNode originalType)
{
Contract.Requires(TypeNode.IsCompleteTemplate(contractClass));
Contract.Requires(TypeNode.IsCompleteTemplate(originalType));
this.parent = parent;
this.contractClass = contractClass;
this.abstractClass = originalType;
}
开发者ID:asvishnyakov,项目名称:CodeContracts,代码行数:9,代码来源:ScrubContractClass.cs
示例3: ConvertToClassParameter
private ClassParameter ConvertToClassParameter(TypeNode typeParameter, InterfaceList interfaces, Class baseClass, ClassExpression cExpr){
ClassParameter cParam = typeParameter is MethodTypeParameter ? new MethodClassParameter() : new ClassParameter();
this.typeParamToClassParamMap[typeParameter.UniqueKey] = cParam;
cParam.SourceContext = typeParameter.SourceContext;
cParam.TypeParameterFlags = ((ITypeParameter)typeParameter).TypeParameterFlags;
if (typeParameter.IsUnmanaged) { cParam.SetIsUnmanaged(); }
cParam.Name = typeParameter.Name;
cParam.Namespace = StandardIds.ClassParameter;
cParam.BaseClass = baseClass == null ? SystemTypes.Object : baseClass;
cParam.BaseClassExpression = cExpr;
cParam.DeclaringMember = ((ITypeParameter)typeParameter).DeclaringMember;
cParam.DeclaringModule = typeParameter.DeclaringModule;
cParam.DeclaringType = typeParameter is MethodTypeParameter ? null : typeParameter.DeclaringType;
cParam.Flags = typeParameter.Flags & ~TypeFlags.Interface;
cParam.ParameterListIndex = ((ITypeParameter)typeParameter).ParameterListIndex;
MemberList mems = cParam.DeclaringType == null ? null : cParam.DeclaringType.Members;
int n = mems == null ? 0 : mems.Count;
for (int i = 0; i < n; i++){
if ((mems[i] as TypeNode) == typeParameter){
mems[i] = cParam;
break;
}
}
if (cExpr != null){
n = interfaces.Count - 1;
InterfaceList actualInterfaces = new InterfaceList(n);
for (int i = 0; i < n; i++)
actualInterfaces.Add(interfaces[i + 1]);
cParam.Interfaces = actualInterfaces;
}else
cParam.Interfaces = interfaces;
if (cExpr != null) cParam.BaseClass = this.VisitClassExpression(cExpr);
return cParam;
}
开发者ID:hesam,项目名称:SketchSharp,代码行数:34,代码来源:Looker.cs
示例4: ClearStatics
private static void ClearStatics()
{
AttributeUsageAttribute = null;
ConditionalAttribute = null;
DefaultMemberAttribute = null;
InternalsVisibleToAttribute = null;
ObsoleteAttribute = null;
GenericICollection = null;
GenericIEnumerable = null;
GenericIList = null;
ICloneable = null;
ICollection = null;
IEnumerable = null;
IList = null;
//Special attributes
AllowPartiallyTrustedCallersAttribute = null;
AssemblyCompanyAttribute = null;
AssemblyConfigurationAttribute = null;
AssemblyCopyrightAttribute = null;
AssemblyCultureAttribute = null;
AssemblyDelaySignAttribute = null;
AssemblyDescriptionAttribute = null;
AssemblyFileVersionAttribute = null;
AssemblyFlagsAttribute = null;
AssemblyInformationalVersionAttribute = null;
AssemblyKeyFileAttribute = null;
AssemblyKeyNameAttribute = null;
AssemblyProductAttribute = null;
AssemblyTitleAttribute = null;
AssemblyTrademarkAttribute = null;
AssemblyVersionAttribute = null;
ClassInterfaceAttribute = null;
CLSCompliantAttribute = null;
ComImportAttribute = null;
ComRegisterFunctionAttribute = null;
ComSourceInterfacesAttribute = null;
ComUnregisterFunctionAttribute = null;
ComVisibleAttribute = null;
DebuggableAttribute = null;
DebuggerHiddenAttribute = null;
DebuggerStepThroughAttribute = null;
DebuggingModes = null;
DllImportAttribute = null;
FieldOffsetAttribute = null;
FlagsAttribute = null;
GuidAttribute = null;
ImportedFromTypeLibAttribute = null;
InAttribute = null;
IndexerNameAttribute = null;
InterfaceTypeAttribute = null;
MethodImplAttribute = null;
NonSerializedAttribute = null;
OptionalAttribute = null;
OutAttribute = null;
ParamArrayAttribute = null;
RuntimeCompatibilityAttribute = null;
SatelliteContractVersionAttribute = null;
SerializableAttribute = null;
SecurityAttribute = null;
SecurityCriticalAttribute = null;
SecurityTransparentAttribute = null;
SecurityTreatAsSafeAttribute = null;
STAThreadAttribute = null;
StructLayoutAttribute = null;
SuppressMessageAttribute = null;
SuppressUnmanagedCodeSecurityAttribute = null;
SecurityAction = null;
//Classes need for System.TypeCode
DBNull = null;
DateTime = null;
TimeSpan = null;
//Classes and interfaces used by the Framework
Activator = null;
AppDomain = null;
ApplicationException = null;
ArgumentException = null;
ArgumentNullException = null;
ArgumentOutOfRangeException = null;
ArrayList = null;
AsyncCallback = null;
Assembly = null;
CodeAccessPermission = null;
CollectionBase = null;
CultureInfo = null;
DictionaryBase = null;
DictionaryEntry = null;
DuplicateWaitObjectException = null;
Environment = null;
EventArgs = null;
ExecutionEngineException = null;
GenericArraySegment = null;
GenericArrayToIEnumerableAdapter = null;
GenericDictionary = null;
GenericIComparable = null;
GenericIComparer = null;
GenericIDictionary = null;
//.........这里部分代码省略.........
开发者ID:armin-bauer,项目名称:SHFB,代码行数:101,代码来源:SystemTypes.cs
示例5: VisitClass
public override Class VisitClass(Class Class) {
PrepareGuardedClass(Class);
return base.VisitClass(Class);
}
开发者ID:hesam,项目名称:SketchSharp,代码行数:4,代码来源:Looker.cs
示例6: CheckForWrapperImplementationsForInheritedInterfaceImplementations
private void CheckForWrapperImplementationsForInheritedInterfaceImplementations(Class Class)
{
Contract.Requires(Class != null);
if (Class.Interfaces == null) return;
if (this.runtimeCheckingLevel == 0) return;
if (!HelperMethods.ContractOption(Class, "runtime", "checking") ||
!HelperMethods.ContractOption(Class, "contract", "inheritance"))
{
return;
}
for (int i = 0; i < Class.Interfaces.Count; i++)
{
var intf = Class.Interfaces[i];
if (intf == null) continue;
CheckForWrapperImplementationsForInheritedInterfaceImplementations(Class, intf);
}
}
开发者ID:Yatajga,项目名称:CodeContracts,代码行数:22,代码来源:PostExtractorChecker.cs
示例7: VisitClass
public override Class VisitClass(Class Class)
{
Class = base.VisitClass(Class);
Class.Template = null;
return Class;
}
开发者ID:flcdrg,项目名称:CodeContracts,代码行数:8,代码来源:DuplicatorForContractsAndClosures.cs
示例8: AddReadContent
void AddReadContent(Class serializer, Block block, TypeNode type, StatementList statements, Identifier reader,
Expression target, Expression required, Expression result, SchemaValidator validator) {
// position us in the content.
statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(reader, Identifier.For("MoveToContent")), new ExpressionList())));
Local elementName = new Local(Identifier.Empty,SystemTypes.String);
statements.Add(new AssignmentStatement(elementName, new QualifiedIdentifier(reader, Identifier.For("LocalName"))));
// make sure the element is not empty.
If isEmpty = AddEmptyElementCheck(statements, reader);
// Read the contents.
statements = isEmpty.FalseBlock.Statements;
statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(reader, Identifier.For("Read")), new ExpressionList())));
statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(reader, Identifier.For("MoveToContent")), new ExpressionList())));
ValidationState context = new ValidationState();
context.ErrorHandler = this.errorHandler;
validator.validator.InitValidation(context);
ArrayList members = null;
if (validator.validator is AllElementsContentValidator) {
members = validator.validator.ExpectedElements(context, false, false);
AddReadAllGroup(serializer, block, type, statements, reader, target, required, result, members, validator.validator.MixedMember);
} else {
// There should be one root level anonymous Item0 member.
SequenceNode seq = (SequenceNode)validator.RootNode; // this is a wrapper node.
if (seq == null) {
// perhaps it is ContentType.Empty or Mixed.
if (validator.validator.ContentType == XmlSchemaContentType.Mixed ||
validator.validator.ContentType == XmlSchemaContentType.TextOnly){
Debug.Assert(validator.validator.MixedMember != null);
statements.Add(new AssignmentStatement(GetMemberBinding(target, validator.validator.MixedMember),
new MethodCall(new QualifiedIdentifier(reader, Identifier.For("ReadStringElement")), new ExpressionList())));
}
return;
} else {
ContentNode n = seq.LeftChild;
AddReadContentNode(n, block, statements, reader, target, required, result, validator);
}
}
// consume final end tag
statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(reader, Identifier.For("ReadEndTag")), new ExpressionList(elementName))));
}
开发者ID:hesam,项目名称:SketchSharp,代码行数:45,代码来源:Serializer.cs
示例9: VisitClass
public override Class VisitClass(Class Class)
{
WriteStart("class {0}", Class.Name.Name);
if (this.braceOnNewLine)
{
WriteFinish(string.Empty);
WriteLine("{");
}
else
WriteFinish(" {");
In();
Class.Members = this.VisitMemberList(Class.Members);
Out();
WriteLine("};");
return Class;
}
开发者ID:ZingModelChecker,项目名称:Zing,代码行数:19,代码来源:ZDecompiler.cs
示例10: ProcessOldExpressionsInAsync
private Block ProcessOldExpressionsInAsync(Method method, EnsuresList asyncpostconditions, Dictionary<TypeNode, Local> closureLocals, ref int oldLocalNameCounter, Class asyncClosure)
{
Contract.Requires(asyncpostconditions != null);
CollectOldExpressions coe = new CollectOldExpressions(
this.module,
method,
this.rewriterNodes,
closureLocals,
oldLocalNameCounter,
asyncClosure
);
foreach (Ensures e in asyncpostconditions)
{
if (!EmitEnsures(e, method.DeclaringType, this.skipQuantifiers)) continue;
coe.Visit(e);
}
oldLocalNameCounter = coe.Counter;
var oldAssignments = coe.PrestateValuesOfOldExpressions;
// don't wrap in a try catch if the method is a constructor (peverify issue)
if (!(method is InstanceInitializer))
{
WrapOldAssignmentsInTryCatch(method, oldAssignments);
}
return oldAssignments;
}
开发者ID:nbulp,项目名称:CodeContracts,代码行数:25,代码来源:Rewriter.cs
示例11: GetRuntimeContractsAttributeCtor
/// <summary>
/// Tries to reuse or create the attribute
/// </summary>
private static InstanceInitializer GetRuntimeContractsAttributeCtor(AssemblyNode assembly)
{
EnumNode runtimeContractsFlags = assembly.GetType(ContractNodes.ContractNamespace, Identifier.For("RuntimeContractsFlags")) as EnumNode;
Class RuntimeContractsAttributeClass = assembly.GetType(ContractNodes.ContractNamespace, Identifier.For("RuntimeContractsAttribute")) as Class;
if (runtimeContractsFlags == null)
{
#region Add [Flags]
Member flagsConstructor = RewriteHelper.flagsAttributeNode.GetConstructor();
AttributeNode flagsAttribute = new AttributeNode(new MemberBinding(null, flagsConstructor), null, AttributeTargets.Class);
#endregion Add [Flags]
runtimeContractsFlags = new EnumNode(assembly,
null, /* declaringType */
new AttributeList(2),
TypeFlags.Sealed,
ContractNodes.ContractNamespace,
Identifier.For("RuntimeContractsFlags"),
new InterfaceList(),
new MemberList());
runtimeContractsFlags.Attributes.Add(flagsAttribute);
RewriteHelper.TryAddCompilerGeneratedAttribute(runtimeContractsFlags);
runtimeContractsFlags.UnderlyingType = SystemTypes.Int32;
Type copyFrom = typeof(RuntimeContractEmitFlags);
foreach (System.Reflection.FieldInfo fi in copyFrom.GetFields())
{
if (fi.IsLiteral)
{
AddEnumValue(runtimeContractsFlags, fi.Name, fi.GetRawConstantValue());
}
}
assembly.Types.Add(runtimeContractsFlags);
}
InstanceInitializer ctor = (RuntimeContractsAttributeClass == null) ? null : RuntimeContractsAttributeClass.GetConstructor(runtimeContractsFlags);
if (RuntimeContractsAttributeClass == null)
{
RuntimeContractsAttributeClass = new Class(assembly,
null, /* declaringType */
new AttributeList(),
TypeFlags.Sealed,
ContractNodes.ContractNamespace,
Identifier.For("RuntimeContractsAttribute"),
SystemTypes.Attribute,
new InterfaceList(),
new MemberList(0));
RewriteHelper.TryAddCompilerGeneratedAttribute(RuntimeContractsAttributeClass);
assembly.Types.Add(RuntimeContractsAttributeClass);
}
if (ctor == null) {
Block returnBlock = new Block(new StatementList(new Return()));
Block body = new Block(new StatementList());
Block b = new Block(new StatementList());
ParameterList pl = new ParameterList();
Parameter levelParameter = new Parameter(Identifier.For("contractFlags"), runtimeContractsFlags);
pl.Add(levelParameter);
ctor = new InstanceInitializer(RuntimeContractsAttributeClass, null, pl, body);
ctor.Flags = MethodFlags.Assembly | MethodFlags.HideBySig | MethodFlags.SpecialName | MethodFlags.RTSpecialName;
Method baseCtor = SystemTypes.Attribute.GetConstructor();
b.Statements.Add(new ExpressionStatement(new MethodCall(new MemberBinding(null, baseCtor), new ExpressionList(ctor.ThisParameter))));
b.Statements.Add(returnBlock);
body.Statements.Add(b);
RuntimeContractsAttributeClass.Members.Add(ctor);
}
return ctor;
}
开发者ID:nbulp,项目名称:CodeContracts,代码行数:80,代码来源:Rewriter.cs
示例12: FindAndInstantiateBaseClassInvariantMethod
private Method FindAndInstantiateBaseClassInvariantMethod(Class asClass, out Field baseReentrancyFlag)
{
baseReentrancyFlag = null;
if (asClass == null || asClass.BaseClass == null) return null;
if (!this.Emit(RuntimeContractEmitFlags.InheritContracts)) return null; // don't call base class invariant if we don't inherit
var baseClass = asClass.BaseClass;
if (!this.InheritInvariantsAcrossAssemblies && (baseClass.DeclaringModule != asClass.DeclaringModule))
return null;
var result = baseClass.GetMethod(Identifier.For("$InvariantMethod$"), null);
if (result != null && !HelperMethods.IsVisibleFrom(result, asClass)) return null;
if (result == null && baseClass.Template != null)
{
// instantiation of generated method has not happened.
var generic = baseClass.Template.GetMethod(Identifier.For("$InvariantMethod$"), null);
if (generic != null)
{
if (!HelperMethods.IsVisibleFrom(generic, asClass)) return null;
// generate proper reference.
result = GetMethodInstanceReference(generic, baseClass);
}
}
// extract base reentrancy flag
if (result != null) {
var instantiatedParent = result.DeclaringType;
baseReentrancyFlag = instantiatedParent.GetField(Identifier.For("$evaluatingInvariant$"));
if (baseReentrancyFlag == null && baseClass.Template != null)
{
// instantiation of generated baseReentrancy flag has not happened.
var generic = baseClass.Template.GetField(Identifier.For("$evaluatingInvariant$"));
if (generic != null)
{
if (HelperMethods.IsVisibleFrom(generic, asClass))
{
baseReentrancyFlag = GetFieldInstanceReference(generic, baseClass);
}
}
}
}
return result;
}
开发者ID:nbulp,项目名称:CodeContracts,代码行数:47,代码来源:Rewriter.cs
示例13: EmitAsyncClosure
/// <summary>
/// There are 2 cases:
/// 1) Task has no return value. In this case, we emit
/// void CheckMethod(Task t) {
/// var ae = t.Exception as AggregateException;
/// if (ae != null) { ae.Handle(this.CheckException); throw ae; }
/// }
/// bool CheckException(Exception e) {
/// .. check exceptional post
/// }
/// 2) Task(T) returns a T value
/// T CheckMethod(Task t) {
/// try {
/// var r = t.Result;
/// .. check ensures on r ..
/// return r;
/// }
/// catch (AggregateException ae) {
/// ae.Handle(this.CheckException);
/// throw;
/// }
/// }
/// bool CheckException(Exception e) {
/// .. check exceptional post
/// }
/// </summary>
public EmitAsyncClosure(Method from, Rewriter parent)
{
this.fromMethod = from;
this.parent = parent;
this.checkMethodId = Identifier.For("CheckPost");
this.checkExceptionMethodId = Identifier.For("CheckException");
this.declaringType = from.DeclaringType;
var closureName = HelperMethods.NextUnusedMemberName(declaringType, "<" + from.Name.Name + ">AsyncContractClosure");
this.closureClass = new Class(declaringType.DeclaringModule, declaringType, null, TypeFlags.NestedPrivate, null, Identifier.For(closureName), SystemTypes.Object, null, null);
declaringType.Members.Add(this.closureClass);
RewriteHelper.TryAddCompilerGeneratedAttribute(this.closureClass);
this.dup = new Duplicator(this.declaringType.DeclaringModule, this.declaringType);
var taskType = from.ReturnType;
var taskArgs = taskType.TemplateArguments == null ? 0 : taskType.TemplateArguments.Count;
this.AggregateExceptionType = new Cache<TypeNode>(() =>
HelperMethods.FindType(parent.assemblyBeingRewritten, StandardIds.System, Identifier.For("AggregateException")));
this.Func2Type = new Cache<TypeNode>(() =>
HelperMethods.FindType(SystemTypes.SystemAssembly, StandardIds.System, Identifier.For("Func`2")));
if (from.IsGeneric)
{
this.closureClass.TemplateParameters = new TypeNodeList();
var parentCount = this.declaringType.ConsolidatedTemplateParameters == null ? 0 : this.declaringType.ConsolidatedTemplateParameters.Count;
for (int i = 0; i < from.TemplateParameters.Count; i++)
{
var tp = HelperMethods.NewEqualTypeParameter(dup, (ITypeParameter)from.TemplateParameters[i], this.closureClass, parentCount + i);
this.closureClass.TemplateParameters.Add(tp);
}
this.closureClass.IsGeneric = true;
this.closureClass.EnsureMangledName();
this.forwarder = new Specializer(this.declaringType.DeclaringModule, from.TemplateParameters, this.closureClass.TemplateParameters);
this.forwarder.VisitTypeParameterList(this.closureClass.TemplateParameters);
taskType = this.forwarder.VisitTypeReference(taskType);
}
else
{
this.closureClassInstance = this.closureClass;
}
var taskTemplate = HelperMethods.Unspecialize(taskType);
var continueWithCandidates = taskTemplate.GetMembersNamed(Identifier.For("ContinueWith"));
Method continueWithMethod = null;
for (int i = 0; i < continueWithCandidates.Count; i++)
{
var cand = continueWithCandidates[i] as Method;
if (cand == null) continue;
if (taskArgs == 0)
{
if (cand.IsGeneric) continue;
if (cand.ParameterCount != 1) continue;
var p = cand.Parameters[0];
var ptype = p.Type;
var ptypeTemplate = ptype;
while (ptypeTemplate.Template != null)
{
ptypeTemplate = ptypeTemplate.Template;
}
if (ptypeTemplate.Name.Name != "Action`1") continue;
continueWithMethod = cand;
break;
}
else
{
if (!cand.IsGeneric) continue;
if (cand.TemplateParameters.Count != 1) continue;
//.........这里部分代码省略.........
开发者ID:nbulp,项目名称:CodeContracts,代码行数:101,代码来源:Rewriter.cs
示例14: VisitBaseClass
private void VisitBaseClass(Class Class)
{
// F:
Contract.Requires(Class != null);
// make sure the possibly generic base class is rewritten before this class
var baseClass = Class.BaseClass;
if (baseClass == null) return;
while (baseClass.Template is Class)
{
baseClass = (Class)baseClass.Template;
}
// make sure base class is in same assembly
if (Class.DeclaringModule != baseClass.DeclaringModule) return;
VisitClass(baseClass);
}
开发者ID:nbulp,项目名称:CodeContracts,代码行数:19,代码来源:Rewriter.cs
示例15: VisitClass
public override void VisitClass(Class Class)
{
if (Class == null) return;
if (visitedClasses[Class.UniqueKey] != null) return;
visitedClasses[Class.UniqueKey] = Class;
VisitBaseClass(Class);
base.VisitClass(Class);
}
开发者ID:nbulp,项目名称:CodeContracts,代码行数:10,代码来源:Rewriter.cs
示例16: MakeContractException
private Class MakeContractException() {
Class contractExceptionType;
#region If we're rewriting an assembly for v4 or above and it *isn't* Silverlight (so serialization support is needed), then use new embedded dll as the type
if (4 <= TargetPlatform.MajorVersion) {
var iSafeSerializationData = SystemTypes.SystemAssembly.GetType(Identifier.For("System.Runtime.Serialization"), Identifier.For("ISafeSerializationData")) as Interface;
if (iSafeSerializationData != null) {
// Just much easier to write the C# and have the compiler generate everything than to try and create it all manually
System.Reflection.Assembly embeddedAssembly;
Stream embeddedAssemblyStream;
embeddedAssembly = System.Reflection.Assembly.GetExecutingAssembly();
embeddedAssemblyStream = embeddedAssembly.GetManifestResourceStream("Microsoft.Contracts.Foxtrot.InternalException.dll");
byte[] data = new byte[0];
using (var br = new BinaryReader(embeddedAssemblyStream)) {
var len = embeddedAssemblyStream.Length;
if (len < Int32.MaxValue)
data = br.ReadBytes((int)len);
AssemblyNode assemblyNode = AssemblyNode.GetAssembly(data, TargetPlatform.StaticAssemblyCache, true, false, true);
contractExceptionType = assemblyNode.GetType(Identifier.For(""), Identifier.For("ContractException")) as Class;
}
if (contractExceptionType == null)
throw new RewriteException("Tried to create the ContractException type from the embedded dll, but failed");
var d = new Duplicator(this.targetAssembly, this.RuntimeContractType);
d.FindTypesToBeDuplicated(new TypeNodeList(contractExceptionType));
var ct = d.Visit(contractExceptionType);
contractExceptionType = (Class)ct;
contractExceptionType.Flags |= TypeFlags.NestedPrivate;
this.RuntimeContractType.Members.Add(contractExceptionType);
return contractExceptionType;
}
}
#endregion
contractExceptionType = new Class(this.targetAssembly, this.RuntimeContractType, new AttributeList(), TypeFlags.Class | TypeFlags.NestedPrivate | TypeFlags.Serializable, null, Identifier.For("ContractException"), SystemTypes.Exception, null, null);
RewriteHelper.TryAddCompilerGeneratedAttribute(contractExceptionType);
var kindField = new Field(contractExceptionType, null, FieldFlags.Private, Identifier.For("_Kind"), contractNodes.ContractFailureKind, null);
var userField = new Field(contractExceptionType, null, FieldFlags.Private, Identifier.For("_UserMessage"), SystemTypes.String, null);
var condField = new Field(contractExceptionType, null, FieldFlags.Private, Identifier.For("_Condition"), SystemTypes.String, null);
contractExceptionType.Members.Add(kindField);
contractExceptionType.Members.Add(userField);
contractExceptionType.Members.Add(condField);
#region Constructor for setting the fields
var parameters = new ParameterList();
var kindParam = new Parameter(Identifier.For("kind"), this.contractNodes.ContractFailureKind);
var failureParam = new Parameter(Identifier.For("failure"), SystemTypes.String);
var usermsgParam = new Parameter(Identifier.For("usermsg"), SystemTypes.String);
var conditionParam = new Parameter(Identifier.For("condition"), SystemTypes.String);
var innerParam = new Parameter(Identifier.For("inner"), SystemTypes.Exception);
parameters.Add(kindParam);
parameters.Add(failureParam);
parameters.Add(usermsgParam);
parameters.Add(conditionParam);
parameters.Add(innerParam);
var body = new Block(new StatementList());
var ctor = new InstanceInitializer(contractExceptionType, null, parameters, body);
ctor.Flags |= MethodFlags.Public | MethodFlags.HideBySig;
ctor.CallingConvention = CallingConventionFlags.HasThis;
body.Statements.Add(new ExpressionStatement(new MethodCall(new MemberBinding(ctor.ThisParameter, contractExceptionType.BaseClass.GetConstructor(SystemTypes.String, SystemTypes.Exception)), new ExpressionList(failureParam, innerParam))));
body.Statements.Add(new AssignmentStatement(new MemberBinding(ctor.ThisParameter, kindField), kindParam));
body.Statements.Add(new AssignmentStatement(new MemberBinding(ctor.ThisParameter, userField), usermsgParam));
body.Statements.Add(new AssignmentStatement(new MemberBinding(ctor.ThisParameter, condField), conditionParam));
body.Statements.Add(new Return());
contractExceptionType.Members.Add(ctor);
#endregion
if (SystemTypes.SerializationInfo != null && SystemTypes.SerializationInfo.BaseClass != null) {
// Silverlight (e.g.) is a platform that doesn't support serialization. So check to make sure the type really exists.
//
var baseCtor = SystemTypes.Exception.GetConstructor(SystemTypes.SerializationInfo, SystemTypes.StreamingContext);
if (baseCtor != null) {
#region Deserialization Constructor
parameters = new ParameterList();
var info = new Parameter(Identifier.For("info"), SystemTypes.SerializationInfo);
var context = new Parameter(Identifier.For("context"), SystemTypes.StreamingContext);
parameters.Add(info);
parameters.Add(context);
body = new Block(new StatementList());
ctor = new InstanceInitializer(contractExceptionType, null, parameters, body);
ctor.Flags |= MethodFlags.Private | MethodFlags.HideBySig;
ctor.CallingConvention = CallingConventionFlags.HasThis;
// : base(info, context)
body.Statements.Add(new ExpressionStatement(new MethodCall(new MemberBinding(ctor.ThisParameter, baseCtor), new ExpressionList(info, context))));
// _Kind = (ContractFailureKind)info.GetInt32("Kind");
var getInt32 = SystemTypes.SerializationInfo.GetMethod(Identifier.For("GetInt32"), SystemTypes.String);
body.Statements.Add(new AssignmentStatement(
new MemberBinding(new This(), kindField),
new MethodCall(new MemberBinding(info, getInt32), new ExpressionList(new Literal("Kind", SystemTypes.String)))
));
// _UserMessage = info.GetString("UserMessage");
var getString = SystemTypes.SerializationInfo.GetMethod(Identifier.For("GetString"), SystemTypes.String);
body.Statements.Add(new AssignmentStatement(
new MemberBinding(new This(), userField),
new MethodCall(new MemberBinding(info, getString), new ExpressionList(new Literal("UserMessage", SystemTypes.String)))
));
// _Condition = info.GetString("Condition");
//.........这里部分代码省略.........
开发者ID:nbulp,项目名称:CodeContracts,代码行数:101,代码来源:Rewriter.cs
示例17: TryAddCompilerGeneratedAttribute
internal static void TryAddCompilerGeneratedAttribute(Class Class)
{
Contract.Requires(Class != null);
TryAddCompilerGeneratedAttribute(Class, System.AttributeTargets.Class);
}
开发者ID:nbulp,项目名称:CodeContracts,代码行数:6,代码来源:RewriteUtils.cs
示例18: CreateWrapperClass
private Class CreateWrapperClass(Class c)
{
var flags = WrapperTypeFlags(c);
var wrapper = new Class(this.assemblyBeingRewritten, null, null, flags, null, c.Name, SystemTypes.Object, null, null);
RewriteHelper.TryAddCompilerGeneratedAttribute(wrapper);
if (c.TemplateParameters != null)
{
Duplicator d = new Duplicator(this.assemblyBeingRewritten, wrapper);
d.FindTypesToBeDuplicated(c.TemplateParameters);
var templateParams = CopyTypeParameterList(wrapper, c, d);
wrapper.TemplateParameters = templateParams;
wrapper.IsGeneric = true;
}
return wrapper;
}
开发者ID:nbulp,项目名称:CodeContracts,代码行数:15,代码来源:Rewriter.cs
示例19: CreateSerializerFor
internal Class CreateSerializerFor(TypeNode type) {
// todo: look in the genCache for other serializer assemblies that may have already
// created the serializer for this type and make an assembly reference to that
// serializer instead of creating a complete duplicate.
TypeNode saved = tempChecker.currentType;
Class c = (Class)serializers[type];
if (c != null) return c;
c = new Class();
c.Flags = TypeFlags.Class | TypeFlags.BeforeFieldInit;
// copy the accessibility of the type we are serializing.
c.Flags |= (type.Flags & (TypeFlags.Public | TypeFlags.NestedAssembly));
c.Name = Identifier.For(GetSerializerName(type));
c.Namespace = Identifier.For(GetSerializerNamespace(type));
c.DeclaringModule = this.module;
c.Members = new MemberList();
c.Attributes = new AttributeList();
c.BaseClass = Runtime.XmlSerializer;
tempChecker.currentType = c;
InstanceInitializer ii = Runtime.XmlSerializerAttribute.GetConstructor();
MemberBinding mb = new MemberBinding(null, ii);
mb.Type = Runtime.XmlSerializerAttribute;
c.Attributes.Add(new AttributeNode(mb, null));
if (cunit != null) {
cunit.Namespaces[0].Types.Add(c);
}
this.module.Types.Add(c);
Identifier typeId = Identifier.For("type"); // what we are writing to.
Identifier rootName = Identifier.For("rootName"); // what we are writing to.
Identifier rootNamespace = Identifier.For("rootNamespace"); // what we are writing to.
// Constructor
Method constructor = new InstanceInitializer();
constructor.Name = StandardIds.Ctor;
constructor.DeclaringType = c;
constructor.Flags = MethodFlags.Public|MethodFlags.HideBySig|MethodFlags.SpecialName|MethodFlags.RTSpecialName;
constructor.Parameters = new ParameterList();
constructor.Parameters.Add(new Parameter(new AttributeList(), ParameterFlags.In, typeId, SystemTypes.Type, null, null));
constructor.Parameters.Add(new Parameter(new AttributeList(), ParameterFlags.In, rootName, SystemTypes.String, null, null));
constructor.Parameters.Add(new Parameter(new AttributeList(), ParameterFlags.In, rootNamespace, SystemTypes.String, null, null));
constructor.ReturnType = SystemTypes.Void;
c.Members.Add(constructor);
// pass args thru to base XmlSerializer constructor.
Block b = constructor.Body = new Block(new StatementList());
b.Statements.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(new Base(), StandardIds.Ctor),
new ExpressionList(typeId, rootName, rootNamespace), NodeType.Call)));
//AddConsoleWrite(b.Statements, new Literal("Hello!!",SystemTypes.String));
// Serialize(T source, XmlSerializationWriter writer) method
Identifier src = Identifier.For("source"); // object being serialized.
Identifier writer = Identifier.For("writer"); // what we are writing to.
Method serialize = new Method();
serialize.Name = Identifier.For("Serialize");
serialize.DeclaringType = c;
serialize.Flags = MethodFlags.Public|MethodFlags.Static|MethodFlags.HideBySig;
serialize.Parameters = new ParameterList();
serialize.Parameters.Add(new Parameter(new AttributeList(), ParameterFlags.In, src, type, null, null));
serialize.Parameters.Add(new Parameter(new AttributeList(), ParameterFlags.In, writer, Runtime.XmlSerializationWriter, null, null));
serialize.Parameters.Add(new Parameter(new AttributeList(), ParameterFlags.In, rootName, SystemTypes.String, null, null));
serialize.Parameters.Add(new Parameter(new AttributeList(), ParameterFlags.In, rootNamespace, SystemTypes.String, null, null));
serialize.ReturnType = SystemTypes.Void;
c.Members.Add(serialize);
// T Deserialize(XmlReader reader, bool required, out bool result) method
Identifier reader = Identifier.For("reader"); // what we are reading from.
Identifier required = Identifier.For("required"); // whether an object is required or not.
Identifier result = Identifier.For("result"); // whether we found anything.
Method deserialize = new Method();
deserialize.Name = Identifier.For("Deserialize");
deserialize.DeclaringType = c;
deserialize.Flags = MethodFlags.Public|MethodFlags.Static|MethodFlags.HideBySig;
deserialize.Parameters = new ParameterList();
deserialize.Parameters.Add(new Parameter(new AttributeList(), ParameterFlags.In, reader, Runtime.XmlSerializationReader, null, null));
deserialize.Parameters.Add(new Parameter(new AttributeList(), ParameterFlags.In, required, SystemTypes.Boolean, null, null));
deserialize.Parameters.Add(new Parameter(new AttributeList(), ParameterFlags.Out, result, SystemTypes.Boolean.GetReferenceType(), null, null));
deserialize.ReturnType = type;
c.Members.Add(deserialize);
// It is important that we add the serializer to the cache AFTER we create the methods, but
// BEFORE we create the method bodies so that we can handle recurrsive calls to AddCallSerializer which
// happens in recurrsive structures like "class Foo { public Foo f; }". Otherwise we'd get stuck in an
// infinite loop.
serializers[type] = c;
// Body of serialize method.
b = serialize.Body = new Block(new StatementList());
StatementList statements = b.Statements;
if (!AddWriteSimpleType(type, statements, c, writer, src, rootName, rootNamespace)) {
MethodCall call = new MethodCall();
call.Callee = new QualifiedIdentifier(writer,Identifier.For("WriteStartElement"));
call.Operands = new ExpressionList();
call.Operands.Add(rootName);
call.Operands.Add(rootNamespace);
statements.Add(new If(new BinaryExpression(rootName,Literal.Null,NodeType.Ne),
//.........这里部分代码省略.........
开发者ID:hesam,项目名称:SketchSharp,代码行数:101,代码来源:Serializer.cs
|
请发表评论