本文整理汇总了C#中Person.GetType方法的典型用法代码示例。如果您正苦于以下问题:C# Person.GetType方法的具体用法?C# Person.GetType怎么用?C# Person.GetType使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Person
的用法示例。
在下文中一共展示了Person.GetType方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: LetsAddColumns
/// <summary>
/// This method demonstrates manipulation of columns.
/// </summary>
public static void LetsAddColumns()
{
// since we will be using the person class a lot we will define just one template.
var person = new Person();
// again we will create a table
DatabaseSession.Instance.Connector.CreateTable(person);
// an empty table is of little use, so lets add all the columns. The first argument passes in the property
// of the class the column will be based upon. The column will be named identically but with all small letters.
// The type of the saved property will be determined automatically from the property's type.
DatabaseSession.Instance.Connector.CreateColumn(person.GetType().GetProperty("Id"), person); // creates column 'id'
DatabaseSession.Instance.Connector.CreateColumn(person.GetType().GetProperty("FirstName"), person); // creates column 'firstname'
// the above is a tedious process but is the preferred way for migrations as you are then able to record all changes within the
// class. Lets quickly clean up.
DatabaseSession.Instance.Connector.DeleteTable(person);
// there is a faster way which you have to be carefull in using.
DatabaseSession.Instance.Connector.CreateTableWithColumns(person);
// that will create the table and ALL properties of the class as columns. If you use this method in migrations, you only need to do it once, the very first time you
// create the table.
// Lets quickly clean up.
DatabaseSession.Instance.Connector.DeleteTable(person);
}
示例2: Love
public override void Love(Person p)
{
if (p.GetType() == this.GetType())
{
s = " loves ";
}
else
{
s = " does not love ";
}
Console.WriteLine(this.GetType().Name + s + p.GetType().Name);
}
示例3: Main
public static void Main()
{
Console.WriteLine("**** Fun with System.Object ****\n");
Person p1 = new Person();
Console.WriteLine("ToString: {0}", p1.ToString());
Console.WriteLine("ToString: {0}", p1.GetHashCode());
Console.WriteLine("ToString: {0}", p1.GetType());
}
示例4: DoSomthing
/// <summary>
/// Do something with the object
/// </summary>
/// <param name="o">The object to do something important</param>
/// <returns>Return null</returns>
public static string DoSomthing(object o)
{
var p = new Person("Torres", "Frederic");
foreach(var propertyInfo in p.GetType().GetProperties()){
Console.WriteLine(propertyInfo.Name + " = "+ propertyInfo.GetValue(p, null).ToString());
}
return null;
}
示例5: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
Person person = new Person();
person.Name = "webabcd";
person.Age = 27;
HttpContext.Current.Response.ClearContent();
// HttpContext.Current.Response.ContentType = "application/json";
HttpContext.Current.Response.ContentType = "text/plain";
// 把person对象序列化成JSON
System.Runtime.Serialization.DataContractJsonSerializer dcjs = new System.Runtime.Serialization.DataContractJsonSerializer(person.GetType());
dcjs.WriteObject(HttpContext.Current.Response.OutputStream, person);
HttpContext.Current.Response.End();
}
示例6: Main
static void Main()
{
var me = new Person
{
FirstName = "Brook",
LastName = "H.",
Age = 39
};
//This is what system.IO is reading from the program as it communicates with the parser.
var serializer = new DataContractSerializer(me.GetType());
var someRam = new MemoryStream();
someRam.WriteObject(someRam, me);
someRam.Seek(0, SeekOrigin.Begin);
Console.WriteLine(XElement.Parse(Encoding.ASCII.GetString(someRam.GetBuffer()).Replace("\0", "")));
}
示例7: registerPerson
public bool registerPerson(Person person)
{
int agentID = person.getAgentID();
try
{
TextWriter tw = new StreamWriter(@"Z:\Downloads\" + agentID + ".txt");
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(person.GetType());
x.Serialize(tw, person);
Console.WriteLine("object written to file");
tw.Close();
return true;
}
catch (Exception e)//perguntar ao prof como encontrar erros de fromatacao de maneira decente
{
throw new MyFormatException(e.ToString());//nao sei o que isto escreve lol
}
}
示例8: getPerson
public Person getPerson(int agentID)
{
try{
Person fileP = new Person("John", 0, 0);//perguntar ao prof se existe alternativa a isto
TextReader tr = new StreamReader(@"Z:\Downloads\" + agentID + ".txt");
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(fileP.GetType());
fileP = (Person)x.Deserialize(tr);
Console.WriteLine(fileP.toString());
tr.Close();
return fileP;
}
catch (Exception e)
{
throw new MyFormatException(e.ToString());//nao sei o que isto escreve lol
}
}
示例9: FillAnketa
private static string FillAnketa(_Application app, object templateFileName, Person anketa, string resultPath)
{
_Document doc = null;
var newFileName = resultPath;
if (!newFileName.EndsWith("\\"))
newFileName += "\\";
newFileName += anketa.Surname+" "+anketa.Name;
try
{
doc = app.Documents.Add(ref templateFileName, ref _missingObj, ref _missingObj, ref _missingObj);
var fieldInfos = anketa.GetType().GetFields();
foreach (var info in fieldInfos)
{
var custAttibs = info.GetCustomAttributes(true);
foreach (var oAttr in custAttibs)
{
if (oAttr is StringAttribute)
{
FillField(doc, info, oAttr as StringAttribute, anketa);
}
else if (oAttr is EnumAttribute)
{
CheckSomeBoxes(doc, info, oAttr as EnumAttribute, anketa);
}
else if (oAttr is BoolAttribute)
{
CheckSomeBoxesFromBool(doc, info, oAttr as BoolAttribute, anketa);
}
}
}
object newFn = newFileName;
doc.SaveAs(ref newFn, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj);
}
catch (Exception e)
{
throw new Exception(string.Format("Ошибка '{0}' при заполнении анкеты '{1}' для '{2} {3}'", e.Message + e.StackTrace, templateFileName, anketa.Surname, anketa.Name));
}
finally
{
if (doc != null) doc.Close(ref _falseObj);
}
return newFileName;
}
示例10: InterceptCallToPropertyInNonInterceptedMethod
public void InterceptCallToPropertyInNonInterceptedMethod()
{
bool wasIntercepted = false;
MyInterceptor interceptor = new MyInterceptor();
interceptor.Intercepted += (s, e) =>
{
wasIntercepted = true;
};
Person p = new Person { Name = "John" };
p.SetAgeTo(50);
p = Decorate(p, interceptor);
p.SetAgeTo(100);
var originalObject = p.GetType().GetField("__target").GetValue(p);
var ageInOriginalObject = originalObject.GetType().GetProperty("Age", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(originalObject, null);
Assert.That(ageInOriginalObject, Is.EqualTo(100)); // The value is still 50
Assert.That(wasIntercepted, Is.True); // The call was not intercepted
}
示例11: FillPerson
public Person FillPerson(Person target)
{
var fieldInfos = target.GetType().GetFields();
foreach (var info in fieldInfos)
{
var custAttibs = info.GetCustomAttributes(true);
foreach (var oAttr in custAttibs.OfType<FieldAttribute>())
{
info.SetValue(target, GetFieldValue(oAttr.FieldName));
}
}
var mrz = GetFieldValue("MRZ");
DateTime bd;
if (DateTime.TryParse(target.BirthDate, out bd))
{
if (bd.Year < 1920)
bd = new DateTime(bd.Year + 100, bd.Month, bd.Day);
target.BirthDate = bd.ToShortDateString();
}
return mrz.Length > 0 ? AnalyzeMRZ(target, mrz) : target;
}
示例12: SetProperty_PropertyHasDefaultValue_DefaultValueAttributeDoesNothing
public void SetProperty_PropertyHasDefaultValue_DefaultValueAttributeDoesNothing()
{
// Arrange
var model = new Person();
var bindingContext = CreateContext(GetMetadataForType(model.GetType()), model);
var metadataProvider = bindingContext.OperationBindingContext.MetadataProvider;
var modelExplorer = metadataProvider.GetModelExplorerForType(typeof(Person), model);
var propertyMetadata = bindingContext.ModelMetadata.Properties[nameof(model.PropertyWithDefaultValue)];
var result = new ModelBindingResult(model: null, isModelSet: false, key: "foo");
var testableBinder = new TestableMutableObjectModelBinder();
// Act
testableBinder.SetProperty(bindingContext, modelExplorer, propertyMetadata, result);
// Assert
var person = Assert.IsType<Person>(bindingContext.Model);
Assert.Equal(0m, person.PropertyWithDefaultValue);
Assert.True(bindingContext.ModelState.IsValid);
}
示例13: ProcessResults_ProvideRequiredFields_Success
public void ProcessResults_ProvideRequiredFields_Success()
{
// Arrange
var model = new Person();
var containerMetadata = GetMetadataForType(model.GetType());
var bindingContext = CreateContext(containerMetadata, model);
var modelStateDictionary = bindingContext.ModelState;
var results = containerMetadata.Properties.ToDictionary(
property => property,
property => new ModelBindingResult(model: null, key: property.PropertyName, isModelSet: false));
var testableBinder = new TestableMutableObjectModelBinder();
// Make ValueTypeRequired valid.
var propertyMetadata = containerMetadata.Properties[nameof(Person.ValueTypeRequired)];
results[propertyMetadata] = new ModelBindingResult(
model: 41,
isModelSet: true,
key: "theModel." + nameof(Person.ValueTypeRequired));
// Make ValueTypeRequiredWithDefaultValue valid.
propertyMetadata = containerMetadata.Properties[nameof(Person.ValueTypeRequiredWithDefaultValue)];
results[propertyMetadata] = new ModelBindingResult(
model: 57,
isModelSet: true,
key: "theModel." + nameof(Person.ValueTypeRequiredWithDefaultValue));
// Also remind ProcessResults about PropertyWithDefaultValue -- as BindPropertiesAsync() would.
propertyMetadata = containerMetadata.Properties[nameof(Person.PropertyWithDefaultValue)];
results[propertyMetadata] = new ModelBindingResult(
model: null,
isModelSet: false,
key: "theModel." + nameof(Person.PropertyWithDefaultValue));
var modelValidationNode = new ModelValidationNode(string.Empty, containerMetadata, model);
// Act
testableBinder.ProcessResults(bindingContext, results, modelValidationNode);
// Assert
Assert.True(modelStateDictionary.IsValid);
Assert.Empty(modelStateDictionary);
// Model gets provided values.
Assert.Equal(41, model.ValueTypeRequired);
Assert.Equal(57, model.ValueTypeRequiredWithDefaultValue);
Assert.Equal(0m, model.PropertyWithDefaultValue); // [DefaultValue] has no effect
}
示例14: ProcessResults_ValueTypeProperty_NoValue_NoError
public void ProcessResults_ValueTypeProperty_NoValue_NoError()
{
// Arrange
var model = new Person();
var containerMetadata = GetMetadataForType(model.GetType());
var bindingContext = CreateContext(containerMetadata, model);
var modelState = bindingContext.ModelState;
var results = containerMetadata.Properties.ToDictionary(
property => property,
property => new ModelBindingResult(model: null, key: property.PropertyName, isModelSet: false));
var testableBinder = new TestableMutableObjectModelBinder();
// Make ValueTypeRequired invalid.
var propertyMetadata = containerMetadata.Properties[nameof(Person.ValueTypeRequired)];
results[propertyMetadata] = new ModelBindingResult(
model: null,
isModelSet: false,
key: "theModel." + nameof(Person.ValueTypeRequired));
// Make ValueTypeRequiredWithDefaultValue invalid
propertyMetadata = containerMetadata.Properties[nameof(Person.ValueTypeRequiredWithDefaultValue)];
results[propertyMetadata] = new ModelBindingResult(
model: null,
isModelSet: false,
key: "theModel." + nameof(Person.ValueTypeRequiredWithDefaultValue));
var modelValidationNode = new ModelValidationNode(string.Empty, containerMetadata, model);
// Act
testableBinder.ProcessResults(bindingContext, results, modelValidationNode);
// Assert
Assert.True(modelState.IsValid);
}
示例15: SetProperty_PropertyIsPreinitialized_NoValue_DoesNothing
public void SetProperty_PropertyIsPreinitialized_NoValue_DoesNothing()
{
// Arrange
var model = new Person();
var bindingContext = CreateContext(GetMetadataForType(model.GetType()), model);
var metadataProvider = bindingContext.OperationBindingContext.MetadataProvider;
var metadata = metadataProvider.GetMetadataForType(typeof(Person));
var propertyMetadata = metadata.Properties[nameof(model.PropertyWithInitializedValue)];
// The null model value won't be used because IsModelBound = false.
var result = ModelBindingResult.Failed("foo");
var testableBinder = new TestableMutableObjectModelBinder();
// Act
testableBinder.SetProperty(bindingContext, metadata, propertyMetadata, result);
// Assert
var person = Assert.IsType<Person>(bindingContext.Model);
Assert.Equal("preinitialized", person.PropertyWithInitializedValue);
Assert.True(bindingContext.ModelState.IsValid);
}