PropertyInfo.SetValue 方法(System.Reflection) | Microsoft Docs

文章推薦指數: 80 %
投票人數:10人

StaticProperty); // Get a type object that represents the Example type. Type examType = typeof(Example); // Change the static property value. 跳到主要內容 已不再支援此瀏覽器。

請升級至MicrosoftEdge,以利用最新功能、安全性更新和技術支援。

下載MicrosoftEdge 其他資訊 目錄 結束焦點模式 語言 閱讀英文 儲存 編輯 共用 Twitter LinkedIn Facebook 電子郵件 WeChat 目錄 語言 語言 閱讀英文 儲存 目錄 閱讀英文 儲存 編輯 Twitter LinkedIn Facebook 電子郵件 WeChat 目錄 PropertyInfo.SetValue方法 參考 此頁面有所助益嗎? Yes No 還有其他意見反應嗎? 系統會將意見反應傳送給Microsoft:按下[提交]按鈕,您的意見反應將用來改善Microsoft產品和服務。

隱私權原則。

送出 謝謝。

定義 命名空間: System.Reflection 組件:System.Reflection.dll 組件:System.Runtime.dll 組件:mscorlib.dll 組件:netstandard.dll 重要 部分資訊涉及發行前產品,在發行之前可能會有大幅修改。

Microsoft對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。

設定指定之物件的屬性值。

本文內容 多載 SetValue(Object,Object) 設定指定之物件的屬性值。

SetValue(Object,Object,Object[]) 使用索引屬性的選擇性索引值,設定指定的物件的屬性值。

SetValue(Object,Object,BindingFlags,Binder,Object[],CultureInfo) 當在衍生類別中覆寫時,設定指定的物件的屬性值,此物件具有指定的繫結、索引和文化特性特定資訊。

SetValue(Object,Object) 設定指定之物件的屬性值。

public: voidSetValue(System::Object^obj,System::Object^value); publicvoidSetValue(objectobj,objectvalue); publicvoidSetValue(object?obj,object?value); memberthis.SetValue:obj*obj->unit PublicSubSetValue(objAsObject,valueAsObject) 參數 obj Object 將設定其屬性值的物件。

value Object 新的屬性值。

例外狀況 ArgumentException 找不到屬性的set存取子。

-或- value無法轉換成PropertyType類型。

TargetException obj類型不符合目標類型,或屬性是執行個體屬性但obj為null。

注意:在.net中,WindowsStore應用程式或便攜類別庫中,改為攔截Exception。

MethodAccessException 曾不合法嘗試存取類別內的私用或保護方法。

注意:在.net中WindowsStore應用程式或可移植類別庫中,改為攔截基類例外狀況MemberAccessException。

TargetInvocationException 設定屬性值時發生錯誤。

InnerException屬性指出錯誤的原因。

範例 下列範例會宣告一個名為Example的類別,其中包含一個staticSharedVisualBasic)的(和一個實例屬性。

此範例會使用SetValue(Object,Object)方法來變更原始的屬性值,並顯示原始和最終的值。

usingnamespaceSystem; usingnamespaceSystem::Reflection; refclassExample { private: intstatic_sharedProperty=41; int_instanceProperty; public: Example() { _instanceProperty=42; }; staticpropertyintSharedProperty { intget(){return_sharedProperty;} voidset(intvalue){_sharedProperty=value;} }; propertyintInstanceProperty { intget(){return_instanceProperty;} voidset(intvalue){_instanceProperty=value;} }; }; voidmain() { Console::WriteLine("Initialvalueofstaticproperty:{0}", Example::SharedProperty); PropertyInfo^piShared= Example::typeid->GetProperty("SharedProperty"); piShared->SetValue(nullptr,76,nullptr); Console::WriteLine("Newvalueofstaticproperty:{0}", Example::SharedProperty); Example^exam=gcnewExample(); Console::WriteLine("\nInitialvalueofinstanceproperty:{0}", exam->InstanceProperty); PropertyInfo^piInstance= Example::typeid->GetProperty("InstanceProperty"); piInstance->SetValue(exam,37,nullptr); Console::WriteLine("Newvalueofinstanceproperty:{0}", exam->InstanceProperty); }; /*Theexampledisplaysthefollowingoutput: Initialvalueofstaticproperty:41 Newvalueofstaticproperty:76 Initialvalueofinstanceproperty:42 Newvalueofinstanceproperty:37 */ usingSystem; usingSystem.Reflection; classExample { privatestaticint_staticProperty=41; privateint_instanceProperty=42; //Declareapublicstaticproperty. publicstaticintStaticProperty { get{return_staticProperty;} set{_staticProperty=value;} } //Declareapublicinstanceproperty. publicintInstanceProperty { get{return_instanceProperty;} set{_instanceProperty=value;} } publicstaticvoidMain() { Console.WriteLine("Initialvalueofstaticproperty:{0}", Example.StaticProperty); //GetatypeobjectthatrepresentstheExampletype. TypeexamType=typeof(Example); //Changethestaticpropertyvalue. PropertyInfopiShared=examType.GetProperty("StaticProperty"); piShared.SetValue(null,76); Console.WriteLine("Newvalueofstaticproperty:{0}", Example.StaticProperty); //CreateaninstanceoftheExampleclass. Exampleexam=newExample(); Console.WriteLine("\nInitialvalueofinstanceproperty:{0}", exam.InstanceProperty); //Changetheinstancepropertyvalue. PropertyInfopiInstance=examType.GetProperty("InstanceProperty"); piInstance.SetValue(exam,37); Console.WriteLine("Newvalueofinstanceproperty:{0}", exam.InstanceProperty); } } //Theexampledisplaysthefollowingoutput: //Initialvalueofstaticproperty:41 //Newvalueofstaticproperty:76 // //Initialvalueofinstanceproperty:42 //Newvalueofinstanceproperty:37 ImportsSystem.Reflection ClassExample PrivateShared_sharedPropertyAsInteger=41 Private_instancePropertyAsInteger=42 'Declareapublicstatic(shared)property. PublicSharedPropertySharedPropertyAsInteger Get Return_sharedProperty EndGet Set _sharedProperty=Value EndSet EndProperty 'Declareapublicinstanceproperty. PublicPropertyInstancePropertyAsInteger Get Return_instanceProperty EndGet Set _instanceProperty=Value EndSet EndProperty PublicSharedSubMain() Console.WriteLine("Initialvalueofsharedproperty:{0}", Example.SharedProperty) 'GetatypeobjectthatrepresentstheExampletype. DimexamTypeAsType=GetType(Example) 'Changethestatic(shared)propertyvalue. DimpiSharedAsPropertyInfo=examType.GetProperty("SharedProperty") piShared.SetValue(Nothing,76) Console.WriteLine("Newvalueofsharedproperty:{0}", Example.SharedProperty) Console.WriteLine() 'CreateaninstanceoftheExampleclass. DimexamAsNewExample Console.WriteLine("Initialvalueofinstanceproperty:{0}", exam.InstanceProperty) 'Changetheinstancepropertyvalue. DimpiInstanceAsPropertyInfo=examType.GetProperty("InstanceProperty") piInstance.SetValue(exam,37) Console.WriteLine("Newvalueofinstanceproperty:{0}",_ exam.InstanceProperty) EndSub EndClass 'Theexampledisplaysthefollowingoutput: 'Initialvalueofsharedproperty:41 'Newvalueofsharedproperty:76 ' 'Initialvalueofinstanceproperty:42 'Newvalueofinstanceproperty:37 備註 多載會SetValue(Object,Object)設定非索引屬性的值。

若要判斷是否已編制索引屬性,請呼叫GetIndexParameters方法。

如果產生的陣列有0(零)元素,則不會編制屬性的索引。

若要設定已編制索引之屬性的值,請呼叫多載SetValue(Object,Object,Object[])。

如果這個物件的屬性型別PropertyInfo是實值型別,而且value是null,則屬性會設定為該型別的預設值。

這是一個便利的方法,它會呼叫抽象方法的執行時間執行SetValue(Object,Object,BindingFlags,Binder,Object[],CultureInfo),BindingFlags.DefaultBindingFlags並指定參數、fornullBinder、nullforObject[]和nullCultureInfo。

若要使用SetValue方法,請先取得Type代表類別的物件。

從Type取得PropertyInfo物件。

從PropertyInfo物件呼叫SetValue方法。

注意 從.NETFramework2.0ServicePack1開始,如果呼叫者已被授ReflectionPermission與旗標,ReflectionPermissionFlag.RestrictedMemberAccess且非公用成員的授權集受限於呼叫者的授權集或其子集,則可以使用這個方法來存取非公用成員。

(查看反映的安全性考慮。

) 若要使用此功能,您的應用程式應該以.NETFramework3.5或更新版本為目標。

適用於 SetValue(Object,Object,Object[]) 使用索引屬性的選擇性索引值,設定指定的物件的屬性值。

public: virtualvoidSetValue(System::Object^obj,System::Object^value,cli::array<:object>^index); publicvirtualvoidSetValue(objectobj,objectvalue,object[]index); publicvirtualvoidSetValue(object?obj,object?value,object?[]?index); abstractmemberSetValue:obj*obj*obj[]->unit overridethis.SetValue:obj*obj*obj[]->unit PublicOverridableSubSetValue(objAsObject,valueAsObject,indexAsObject()) 參數 obj Object 將設定其屬性值的物件。

value Object 新的屬性值。

index Object[] 索引屬性的選擇性索引值。

非索引屬性的這個值應為null。

實作 SetValue(Object,Object,Object[]) 例外狀況 ArgumentException index陣列未包含所需的引數類型。

-或- 找不到屬性的set存取子。

-或- value無法轉換成PropertyType類型。

TargetException 物件不符合目標類型,或屬性是執行個體屬性但obj為null。

注意:在.net中,WindowsStore應用程式或便攜類別庫中,改為攔截Exception。

TargetParameterCountException index中的參數數目不符合索引屬性所接受的參數數目。

MethodAccessException 曾不合法嘗試存取類別內的私用或保護方法。

注意:在.net中WindowsStore應用程式或可移植類別庫中,改為攔截基類例外狀況MemberAccessException。

TargetInvocationException 設定屬性值時發生錯誤。

例如,為索引屬性指定的索引值超出範圍。

InnerException屬性指出錯誤的原因。

範例 下列範例會定義名為TestClass的類別,該類別具有名為的讀寫屬性Caption。

它會顯示內容的預設值Caption、呼叫SetValue方法來變更屬性值,以及顯示結果。

usingnamespaceSystem; usingnamespaceSystem::Reflection; //Defineaproperty. publicrefclassTestClass { private: String^caption; public: TestClass() { caption="ADefaultcaption"; } propertyString^Caption { String^get() { returncaption; } voidset(String^value) { if(caption!=value) { caption=value; } } } }; intmain() { TestClass^t=gcnewTestClass; //GetthetypeandPropertyInfo. Type^myType=t->GetType(); PropertyInfo^pinfo=myType->GetProperty("Caption"); //Displaythepropertyvalue,usingtheGetValuemethod. Console::WriteLine("\nGetValue:{0}",pinfo->GetValue(t,nullptr)); //UsetheSetValuemethodtochangethecaption. pinfo->SetValue(t,"Thiscaptionhasbeenchanged.",nullptr); //Displaythecaptionagain. Console::WriteLine("GetValue:{0}",pinfo->GetValue(t,nullptr)); Console::WriteLine("\nPresstheEnterkeytocontinue."); Console::ReadLine(); return0; } /* Thisexampleproducesthefollowingoutput: GetValue:ADefaultcaption GetValue:Thiscaptionhasbeenchanged PresstheEnterkeytocontinue. */ usingSystem; usingSystem.Reflection; //Defineaclasswithaproperty. publicclassTestClass { privatestringcaption="ADefaultcaption"; publicstringCaption { get{returncaption;} set { if(caption!=value) { caption=value; } } } } classTestPropertyInfo { publicstaticvoidMain() { TestClasst=newTestClass(); //GetthetypeandPropertyInfo. TypemyType=t.GetType(); PropertyInfopinfo=myType.GetProperty("Caption"); //Displaythepropertyvalue,usingtheGetValuemethod. Console.WriteLine("\nGetValue:"+pinfo.GetValue(t,null)); //UsetheSetValuemethodtochangethecaption. pinfo.SetValue(t,"Thiscaptionhasbeenchanged.",null); //Displaythecaptionagain. Console.WriteLine("GetValue:"+pinfo.GetValue(t,null)); Console.WriteLine("\nPresstheEnterkeytocontinue."); Console.ReadLine(); } } /* Thisexampleproducesthefollowingoutput: GetValue:ADefaultcaption GetValue:Thiscaptionhasbeenchanged PresstheEnterkeytocontinue. */ ImportsSystem.Reflection 'Defineaclasswithaproperty. PublicClassTestClass PrivatemyCaptionAsString="ADefaultcaption" PublicPropertyCaption()AsString Get ReturnmyCaption EndGet Set IfmyCaption<>valueThenmyCaption=value EndSet EndProperty EndClass PublicClassTestPropertyInfo PublicSharedSubMain() DimtAsNewTestClass() 'GetthetypeandPropertyInfo. DimmyTypeAsType=t.GetType() DimpinfoAsPropertyInfo=myType.GetProperty("Caption") 'Displaythepropertyvalue,usingtheGetValuemethod. Console.WriteLine(vbCrLf&"GetValue:"&pinfo.GetValue(t,Nothing)) 'UsetheSetValuemethodtochangethecaption. pinfo.SetValue(t,"Thiscaptionhasbeenchanged.",Nothing) 'Displaythecaptionagain. Console.WriteLine("GetValue:"&pinfo.GetValue(t,Nothing)) Console.WriteLine(vbCrLf&"PresstheEnterkeytocontinue.") Console.ReadLine() EndSub EndClass 'Thisexampleproducesthefollowingoutput: ' 'GetValue:ADefaultcaption 'GetValue:Thiscaptionhasbeenchanged ' 'PresstheEnterkeytocontinue. 請注意,因為屬性不是Caption參數陣列,所以index引數為null。

下列範例會宣告一個名為Example的類別,其中包含三個屬性:staticSharedVisualBasic)中的屬性(、實例屬性和索引的實例屬性。

此範例會使用SetValue方法來變更屬性的預設值,並顯示原始和最終的值。

使用反映來搜尋已編制索引之實例屬性的名稱,會根據語言以及套用至屬性的屬性而不同。

在VisualBasic中,一律會使用屬性名稱來搜尋具有反映的屬性。

您可以使用Default關鍵字將屬性設為預設的索引屬性,在此情況下,您可以在存取屬性時省略名稱,如此範例所示。

您也可以使用屬性名稱。

在c#中,已編制索引的實例屬性是稱為索引子的預設屬性,而且在存取程式碼中的屬性時,絕對不會使用該名稱。

根據預設,屬性的名稱為Item,而且當您使用反映來搜尋屬性時,必須使用該名稱。

您可以使用IndexerNameAttribute屬性,為索引子提供不同的名稱。

在這個範例中,名稱為IndexedInstanceProperty。

在c++中,此default規範可用來讓索引屬性成為預設索引屬性(類別索引子)。

在此情況下,屬性的名稱預設為Item,而且當您使用反映來搜尋屬性時,您必須使用該名稱,如此範例所示。

您可以使用IndexerNameAttribute屬性在反映中為類別索引子提供不同的名稱,但您無法使用該名稱來存取程式碼中的屬性。

不是類別索引子的索引屬性,會在程式碼和反映中使用其名稱進行存取。

usingnamespaceSystem; usingnamespaceSystem::Reflection; usingnamespaceSystem::Collections::Generic; refclassExample { private: intstatic_sharedProperty=41; int_instanceProperty; Dictionary^_indexedInstanceProperty; public: Example() { _instanceProperty=42; _indexedInstanceProperty=gcnewDictionary(); }; staticpropertyintSharedProperty { intget(){return_sharedProperty;} voidset(intvalue){_sharedProperty=value;} }; propertyintInstanceProperty { intget(){return_instanceProperty;} voidset(intvalue){_instanceProperty=value;} }; //Bydefault,thenameofthedefaultindexedproperty(class //indexer)isItem,andthatnamemustbeusedtosearchforthe //propertywithreflection.Thepropertycanbegivenadifferent //namebyusingtheIndexerNameAttributeattribute. propertyString^default[int] { String^get(intkey) { String^returnValue; if(_indexedInstanceProperty->TryGetValue(key,returnValue)) { returnreturnValue; } else { returnnullptr; } } voidset(intkey,String^value) { if(value==nullptr) { throwgcnewArgumentNullException( "IndexedInstancePropertyvaluecanbeanemptystring,butitcannotbenull."); } else { if(_indexedInstanceProperty->ContainsKey(key)) { _indexedInstanceProperty[key]=value; } else { _indexedInstanceProperty->Add(key,value); } } } }; }; voidmain() { Console::WriteLine("Initialvalueofclass-levelproperty:{0}", Example::SharedProperty); PropertyInfo^piShared= Example::typeid->GetProperty("SharedProperty"); piShared->SetValue(nullptr,76,nullptr); Console::WriteLine("Finalvalueofclass-levelproperty:{0}", Example::SharedProperty); Example^exam=gcnewExample(); Console::WriteLine("\nInitialvalueofinstanceproperty:{0}", exam->InstanceProperty); PropertyInfo^piInstance= Example::typeid->GetProperty("InstanceProperty"); piInstance->SetValue(exam,37,nullptr); Console::WriteLine("Finalvalueofinstanceproperty:{0}", exam->InstanceProperty); exam[17]="Stringnumber17"; exam[46]="Stringnumber46"; exam[9]="Stringnumber9"; Console::WriteLine( "\nInitialvalueofindexedinstanceproperty(17):'{0}'", exam[17]); //Bydefault,thenameofthedefaultindexedproperty(class //indexer)isItem,andthatnamemustbeusedtosearchforthe //propertywithreflection.Thepropertycanbegivenadifferent //namebyusingtheIndexerNameAttributeattribute. PropertyInfo^piIndexedInstance= Example::typeid->GetProperty("Item"); piIndexedInstance->SetValue( exam, "Newvalueforstringnumber17", gcnewarray{17}); Console::WriteLine("Finalvalueofindexedinstanceproperty(17):'{0}'", exam[17]); }; /*Thisexampleproducesthefollowingoutput: Initialvalueofclass-levelproperty:41 Finalvalueofclass-levelproperty:76 Initialvalueofinstanceproperty:42 Finalvalueofinstanceproperty:37 Initialvalueofindexedinstanceproperty(17):'Stringnumber17' Finalvalueofindexedinstanceproperty(17):'Newvalueforstringnumber17' */ usingSystem; usingSystem.Reflection; usingSystem.Collections.Generic; usingSystem.Runtime.CompilerServices; classExample { privatestaticint_staticProperty=41; publicstaticintStaticProperty { get { return_staticProperty; } set { _staticProperty=value; } } privateint_instanceProperty=42; publicintInstanceProperty { get { return_instanceProperty; } set { _instanceProperty=value; } } privateDictionary_indexedInstanceProperty= newDictionary(); //Bydefault,theindexerisnamedItem,andthatnamemustbeused //tosearchfortheproperty.Inthisexample,theindexerisgiven //adifferentnamebyusingtheIndexerNameAttributeattribute. [IndexerNameAttribute("IndexedInstanceProperty")] publicstringthis[intkey] { get { stringreturnValue=null; if(_indexedInstanceProperty.TryGetValue(key,outreturnValue)) { returnreturnValue; } else { returnnull; } } set { if(value==null) { thrownewArgumentNullException("IndexedInstancePropertyvaluecanbeanemptystring,butitcannotbenull."); } else { if(_indexedInstanceProperty.ContainsKey(key)) { _indexedInstanceProperty[key]=value; } else { _indexedInstanceProperty.Add(key,value); } } } } publicstaticvoidMain() { Console.WriteLine("Initialvalueofclass-levelproperty:{0}", Example.StaticProperty); PropertyInfopiShared=typeof(Example).GetProperty("StaticProperty"); piShared.SetValue(null,76,null); Console.WriteLine("Finalvalueofclass-levelproperty:{0}", Example.StaticProperty); Exampleexam=newExample(); Console.WriteLine("\nInitialvalueofinstanceproperty:{0}", exam.InstanceProperty); PropertyInfopiInstance= typeof(Example).GetProperty("InstanceProperty"); piInstance.SetValue(exam,37,null); Console.WriteLine("Finalvalueofinstanceproperty:{0}", exam.InstanceProperty); exam[17]="Stringnumber17"; exam[46]="Stringnumber46"; exam[9]="Stringnumber9"; Console.WriteLine( "\nInitialvalueofindexedinstanceproperty(17):'{0}'", exam[17]); //Bydefault,theindexerisnamedItem,andthatnamemustbeused //tosearchfortheproperty.Inthisexample,theindexerisgiven //adifferentnamebyusingtheIndexerNameAttributeattribute. PropertyInfopiIndexedInstance= typeof(Example).GetProperty("IndexedInstanceProperty"); piIndexedInstance.SetValue( exam, "Newvalueforstringnumber17", newobject[]{(int)17}); Console.WriteLine( "Finalvalueofindexedinstanceproperty(17):'{0}'", exam[17]); } } /*Thisexampleproducesthefollowingoutput: Initialvalueofclass-levelproperty:41 Finalvalueofclass-levelproperty:76 Initialvalueofinstanceproperty:42 Finalvalueofinstanceproperty:37 Initialvalueofindexedinstanceproperty(17):'Stringnumber17' Finalvalueofindexedinstanceproperty(17):'Newvalueforstringnumber17' */ ImportsSystem.Reflection ImportsSystem.Collections.Generic ClassExample PrivateShared_sharedPropertyAsInteger=41 PublicSharedPropertySharedPropertyAsInteger Get Return_sharedProperty EndGet Set _sharedProperty=Value EndSet EndProperty Private_instancePropertyAsInteger=42 PublicPropertyInstancePropertyAsInteger Get Return_instanceProperty EndGet Set _instanceProperty=Value EndSet EndProperty Private_indexedInstancePropertyAsNewDictionary(OfInteger,String) DefaultPublicPropertyIndexedInstanceProperty(ByValkeyAsInteger)AsString Get DimreturnValueAsString=Nothing If_indexedInstanceProperty.TryGetValue(key,returnValue)Then ReturnreturnValue Else ReturnNothing EndIf EndGet Set IfValueIsNothingThen ThrowNewArgumentNullException(_ "IndexedInstancePropertyvaluecanbeanemptystring,butitcannotbeNothing.") Else If_indexedInstanceProperty.ContainsKey(key)Then _indexedInstanceProperty(key)=Value Else _indexedInstanceProperty.Add(key,Value) EndIf EndIf EndSet EndProperty SharedSubMain() Console.WriteLine("Initialvalueofclass-levelproperty:{0}",_ Example.SharedProperty) DimpiSharedAsPropertyInfo=_ GetType(Example).GetProperty("SharedProperty") piShared.SetValue(_ Nothing,_ 76,_ Nothing) Console.WriteLine("Finalvalueofclass-levelproperty:{0}",_ Example.SharedProperty) DimexamAsNewExample Console.WriteLine(vbCrLf&_ "Initialvalueofinstanceproperty:{0}",_ exam.InstanceProperty) DimpiInstanceAsPropertyInfo=_ GetType(Example).GetProperty("InstanceProperty") piInstance.SetValue(_ exam,_ 37,_ Nothing) Console.WriteLine("Finalvalueofinstanceproperty:{0}",_ exam.InstanceProperty) exam(17)="Stringnumber17" exam(46)="Stringnumber46" 'InVisualBasic,adefaultindexedpropertycanalsobereferred 'tobyname. exam.IndexedInstanceProperty(9)="Stringnumber9" Console.WriteLine(vbCrLf&_ "Initialvalueofindexedinstanceproperty(17):'{0}'",_ exam(17)) DimpiIndexedInstanceAsPropertyInfo=_ GetType(Example).GetProperty("IndexedInstanceProperty") piIndexedInstance.SetValue(_ exam,_ "Newvalueforstringnumber17",_ NewObject(){CType(17,Integer)}) Console.WriteLine("Finalvalueofindexedinstanceproperty(17):'{0}'",_ exam(17)) EndSub EndClass 'Thisexampleproducesthefollowingoutput: ' 'Initialvalueofclass-levelproperty:41 'Finalvalueofclass-levelproperty:76 ' 'Initialvalueofinstanceproperty:42 'Finalvalueofinstanceproperty:37 ' 'Initialvalueofindexedinstanceproperty(17):'Stringnumber17' 'Finalvalueofindexedinstanceproperty(17):'Newvalueforstringnumber17' 備註 如果這個PropertyInfo物件是實值型別,而且value是null,則屬性會設定為該型別的預設值。

若要判斷是否已編制索引屬性,請使用GetIndexParameters方法。

如果產生的陣列有0(零)元素,則不會編制屬性的索引。

這是一個便利的方法,它會呼叫抽象方法的執行時間執行SetValue(Object,Object,BindingFlags,Binder,Object[],CultureInfo),BindingFlags.DefaultBindingFlags並指定參數、、nullBinder和null的CultureInfo。

若要使用SetValue方法,請先取得Type代表類別的物件。

從Type取得PropertyInfo。

在中PropertyInfo,使用SetValue方法。

注意 從.NETFramework2.0ServicePack1開始,如果呼叫者已被授ReflectionPermission與旗標,ReflectionPermissionFlag.RestrictedMemberAccess且非公用成員的授權集受限於呼叫者的授權集或其子集,則可以使用這個方法來存取非公用成員。

(查看反映的安全性考慮。

) 若要使用此功能,您的應用程式應該以.NETFramework3.5或更新版本為目標。

適用於 SetValue(Object,Object,BindingFlags,Binder,Object[],CultureInfo) 當在衍生類別中覆寫時,設定指定的物件的屬性值,此物件具有指定的繫結、索引和文化特性特定資訊。

public: abstractvoidSetValue(System::Object^obj,System::Object^value,System::Reflection::BindingFlagsinvokeAttr,System::Reflection::Binder^binder,cli::array<:object>^index,System::Globalization::CultureInfo^culture); publicabstractvoidSetValue(object?obj,object?value,System.Reflection.BindingFlagsinvokeAttr,System.Reflection.Binder?binder,object?[]?index,System.Globalization.CultureInfo?culture); publicabstractvoidSetValue(objectobj,objectvalue,System.Reflection.BindingFlagsinvokeAttr,System.Reflection.Binderbinder,object[]index,System.Globalization.CultureInfoculture); abstractmemberSetValue:obj*obj*System.Reflection.BindingFlags*System.Reflection.Binder*obj[]*System.Globalization.CultureInfo->unit PublicMustOverrideSubSetValue(objAsObject,valueAsObject,invokeAttrAsBindingFlags,binderAsBinder,indexAsObject(),cultureAsCultureInfo) 參數 obj Object 將設定其屬性值的物件。

value Object 新的屬性值。

invokeAttr BindingFlags 下列可指定引動過程屬性之列舉成員的位元組合:InvokeMethod、CreateInstance、Static、GetField、SetField、GetProperty或SetProperty。

您必須指定適當的引動過程屬性。

例如,要叫用靜態成員,就設定Static旗標。

binder Binder 使用反映來啟用繫結、強制引數的類型、成員的引動過程,和擷取MemberInfo物件的物件。

如果binder為null,則會使用預設繫結器。

index Object[] 索引屬性的選擇性索引值。

非索引屬性的這個值應為null。

culture CultureInfo 資源要當地語系化的文化特性。

如果未針對這個文化特性將資源當地語系化,則將在搜尋相符項目時持續呼叫Parent屬性。

如果這個值是null,則會從CurrentUICulture屬性取得特定文化特性資訊。

實作 SetValue(Object,Object,BindingFlags,Binder,Object[],CultureInfo) 例外狀況 ArgumentException index陣列未包含所需的引數類型。

-或- 找不到屬性的set存取子。

-或- value無法轉換成PropertyType類型。

TargetException 物件不符合目標類型,或屬性是執行個體屬性但obj為null。

TargetParameterCountException index中的參數數目不符合索引屬性所接受的參數數目。

MethodAccessException 曾不合法嘗試存取類別內的私用或保護方法。

TargetInvocationException 設定屬性值時發生錯誤。

例如,為索引屬性指定的索引值超出範圍。

InnerException屬性指出錯誤的原因。

備註 如果這個PropertyInfo物件是實值型別,而且value是null,則屬性會設定為該型別的預設值。

若要判斷是否已編制索引屬性,請使用GetIndexParameters方法。

如果產生的陣列有0(零)元素,則不會編制屬性的索引。

完全信任的程式碼會略過存取限制。

也就是說,每當程式碼完全受信任時,就可以透過反映來存取及叫用私用的函式、方法、欄位和屬性。

若要使用SetValue方法,請先取得類別Type。

從Type取得PropertyInfo。

在中PropertyInfo,使用SetValue方法。

注意 從.NETFramework2.0ServicePack1開始,如果呼叫者已被授ReflectionPermission與旗標,ReflectionPermissionFlag.RestrictedMemberAccess且非公用成員的授權集受限於呼叫者的授權集或其子集,則可以使用這個方法來存取非公用成員。

(查看反映的安全性考慮。

) 若要使用此功能,您的應用程式應該以.NETFramework3.5或更新版本為目標。

適用於 本文內容



請為這篇文章評分?