문제

I don't have much experience with VB.NET and although I've searched, I can't find an answer to the following:

Say I have a Dim myVar As MyClass, and then a function in which I intend to initialize it such as Public Sub MyInit(ByRef myVar As MyClass). Attempting to call this method is giving me a null reference error in the compiler, stating that I should initialize the variable first (but I intend to put that functionality in my method!).

Any thoughts in how I could achieve what I'm attempting here?

PS: I reckon it'd make more sense to create an Initialize() method in MyClass, or to make a Public Function MyClassInitialize() As MyClass, but in my particular scenario this is not possible.

도움이 되었습니까?

해결책

If you're just worried about the Variable 'myVar' is passed by reference before it has been assigned a value warning, you can just change the declaration to Dim myVar as MyClass = Nothing.

If you're writing the MyInit sub, you could also turn it into a function that returns an instance of MyClass:

Public Function MyInit() As MyClass
    Dim myLocalVar As New MyClass()
    '... initialization here
    Return myLocalVar
End Function

...

Dim myVar As MyClass = MyInit()
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top