Example 2 If the equation
$$
x^{3}-5 x^{2}+(4+k) x-k=0
$$

has three roots that can serve as the lengths of the three sides of an isosceles triangle, then the value of the real number $k$ is ( ).
(A) 3
(B) 4
(C) 5
(D) 6
The original equation can be transformed into
$$
(x-1)\left(x^{2}-4 x+k\right)=0 \text {. }
$$

Given that the three roots of the original equation can serve as the three side lengths of an isosceles triangle, we know that $x=1$ is a root of $x^{2}-4 x+k=0$, or $x^{2}-4 x+k=0$ has two equal roots.
Solving this, we get $k=3$ or 4.
When $k=3$, the three roots of the equation are $1,1,3$, which cannot serve as the side lengths of an isosceles triangle;

When $k=4$, the three roots of the equation are $1, 2, 2$, which can serve as the side lengths of an isosceles triangle.
Therefore, the value of $k$ is 4. Choose B.